C# Reading From NetworkStream using StreamReader - c#

I'm a Java Developer Trying to build a Simple C# TCP Client. however for the life of me I can't figure out how to get this bloody thing to work. Here is my TCPClient code. BTW, I stole this directly from msdn. http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
public static void Connect(String server, int port, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
Here is my Java Server.
private ServerSocket socket;
private JAXBContext jaxbContext;
boolean listening = true;
#SuppressWarnings("unused")
private HMSAgentService() {
}
public HMSAgentService(int port) {
try {
this.socket = new ServerSocket(port);
logger.debug("Agent Service listening on port : " + port);
this.jaxbContext = HMSAgentUtil.getJAXBContext();
while (listening) {
new AgentServiceThread(socket.accept(), jaxbContext).start();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (JAXBException e) {
logger.error(e.getMessage(), e);
}
}
It simply starts off a new thread when it receives a client connection.
Now my problem is that The program never moves past the stream.Write(). Also the server never receives the message. Only after I call Stream.close() does the server receive the message. But that essentially closes the connection and the client can't receive any more messages. Why is happening. I've tried using Sockets, StreamWriters, StreamReaders and its the same story.
At this point i'm contemplating using The Asynchronous method, but I'm trying to keep the program as simple as possible, since there is no need for it. Is there anyway of signaling the end of a Write?

Related

Why my server program prints the first letter of the message I sent from client in C#?

I am trying to send a message from a Socket client I created in C# on an Android device to a TCPListener server on my PC. The message is sent and I can see it printed on the output of the terminal as I programmed it to but now the server prints the first letter of the message only like when I send David, it only prints D. I need help to revise my code and make it print the entire message sent from the Android client. The code for the server program is below
static void Main(string[] args)
{
TcpListener server = null;
try
{
//decide where the aplication will listen for connections
int port = 13000;
IPAddress localAddress = IPAddress.Parse("192.168.49.147");
server = new TcpListener(localAddress, port);
//start listening for client requests
server.Start();
//initialize buffer for reading data received from a client
byte[] bytes = new byte[256];
string? data;
data = null;
//enter into the listening loop
while (true)
{
Console.WriteLine("Listening for connections");
//perform a blocking call to accept requests
//You could also use a server.Accept() to accept an incoming connection
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected");
data = null;
//get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
//loop to receive all the data
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
//translate the byte received into ASCII encoded data
//something is wrong here as it prints the first character of the string
data = System.Text.Encoding.ASCII.GetString(bytes, 0, 1);
Console.WriteLine("Received: {0}", data);
//process the data sent ny the client
data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
//shut down and end connection
client.Close();
}
}catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//stop listening for new connections
server.Stop();
}
}

How do I keep a client socket connection open and send/receive multiple messages in a console app

I am connecting to a server via TCP socket and sending in strings of data and expecting responses. The responses are unique to the request string and there are two responses per request. One that says the server completed an intermediate task and another indicating the task is complete. These tasks take up to about 20 seconds to complete. Note - I have no access to the server program/code its proprietary.
The client should be able to send in string requests anytime and sometimes fairly quickly. Requests could stack up and the client needs to wait for the unique responses to each request as they are received.
Assuming this needs an asynchronous client I am using the example right from the MS site.
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example
Developing in a console app, I am able to connect and send string requests and I get one response back. The program then exits. New to async sockets I'm not sure how to keep the socket "alive" or open and randomly Console.Read new strings, send them, and get both responses as they are received.
Here is my client code.
public static Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
public static void StartClient()
{
// Connect to a remote device.
try
{
IPEndPoint remoteEP = new IPEndPoint(ip, port);
// Create a TCP/IP socket.
Socket client = new Socket(ip.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Console.WriteLine("Enter a message string: \n");
message = Console.ReadLine();
// Send test data to the remote device.
Send(client, message + "\r\n"); // \r\n required for server to know end of string
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Connected to: {0}", client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
// Added this here to see if receiving would continue, does not work
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
At the very least, you could wrap your read-send-receive logic in a loop:
while (true) {
Console.WriteLine("Enter a message string: \n");
message = Console.ReadLine();
if (message == "quit") break;
// Send test data to the remote device.
Send(client, message + "\r\n"); // \r\n required for server to know end of string
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
}
I also recommend that you learn how to use the Task asynchronous programming (TAP) model, which is the recommended approach for new development. TAP uses the async and await keywords, along with the Task classes, to achieve asynchronicity in a concise, readable way.

How to connect SocketIO with C# client

C# I am developing a MIP plugin for Milestone VMS.
I have a problem while connecting to SocketIO with C#.
I have tried to connect to SocketIO with TcpClient, Socket, ClientWebSocket
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1, 3001);
I also have tried to connect with ClientWebSocket but again no reaction in server side.
using (var client = new ClientWebSocket())
{
// await client.ConnectAsync(new Uri("ws://192.168.100.25:8090/?token="),timeout.Token);
await client.ConnectAsync(new Uri(LOCAL_PATH), timeout.Token);
var buffer = new ArraySegment<byte>(new byte[1000]);
var result = await client.ReceiveAsync(buffer, timeout.Token);
}
Can anyone provide some libraries that may serve as clients to SocketIO?
URI has this syntax: http://127.0.0.1:3001?token=xxx
here is a tested code that i use , supposing your server is running , you need to pass the IP or HostName and port number , then come the payload or message that you want to send :
private bool ConnectAndSendMessage(String server, Int32 port, String message)
{
try
{
// Create a TcpClient.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Buffer to store the response bytes receiver from the running server.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
// Close everything.
stream.Close();
client.Close(); return true;
}
catch (ArgumentNullException e)
{
_txtStyling.WriteCustomLine(string.Format("ArgumentNullException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
}
catch (SocketException e)
{
_txtStyling.WriteCustomLine(string.Format("SocketException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
}
}

Sending a packet in C# via TCP?

I'll try and explain my question below, I have tried googling for an answer but firstly, I don't really know what I should be googling and I haven't found anything that makes sense to me, I was wondering if someone could explain it? Many Thanks.
Hello. I am trying to send a simple network packet using TCP, I have done it using UDP pretty easily as its really easy with UDP, I was wondering if anyone could help me do the equivalent in TCP? I tried using a TcpClient, but it doesn't have a Send method the same as UDP?
public void OnUdp()
{
var client = new UdpClient(Host, Port);
client.Send(rubbish, rubbish.Length);
}
This is the example from https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}

Message not received TCP

My IP-Camera is configured to send alarm messages to my computer.
IPAddress of camera: 10.251.51.1
IPAddress of my computer: 10.251.51.136
The camera can be configured to send messages to any port on my computer.
So, I set the alarm destination to my computer's IP Address: 10.251.51.136 at port 3487.
Now, what should be done at my computer to get the message sent by the camera ?
I tried to write a TCPListener from MSDN and the code is below:
Int32 port = 3487;
IPAddress localAddr = IPAddress.Parse("10.251.51.136");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
server.Start();
// Start listening for client requests.
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
server.Start();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
But this does not seem to be working.
Or is my entire approach flawed ? Should i implement TCPListener or TCPServer instead for my scenario above?
Any pointers why?

Categories