C# socket problem - c#

I am creating a socket server in C# and a client in PHP. The conversation between client and server is something like this:
client connects
server sends welcome message
client sends data
server sends response
(repeat step 3 - 4 until client disconnects)
It works until step 3. The data from the client is received by the server. However, the client waits forever until the server sends its response and eventually times out.
Here is the relevant C# code:
class Program
{
private const int CONNECT_QUEUE_LENGTH = 4;
static void ListenForRequests()
{
Socket listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSock.Bind(new IPEndPoint(IPAddress.Any, 9999));
listenSock.Listen(CONNECT_QUEUE_LENGTH);
listenSock.Blocking = true;
byte[] data = new byte[1024];
while (true)
{
Socket newConnection = listenSock.Accept();
newConnection.Blocking = true;
// Create new thread for each request
var t = new Thread(() => new RequestHandler(newConnection));
t.Start();
}
}
}
class RequestHandler
{
public RequestHandler(Socket socket)
{
Util.WriteToSocket("A message", socket);
Console.WriteLine("Received: " + Util.ReadSocketToEnd(socket).Length);
Util.WriteToSocket("Fin!", socket);
}
}
static class Util
{
public static string ReadSocketToEnd(Socket newConnection)
{
var sb = new StringBuilder();
byte[] data = new byte[1024];
int receivedDataLength = newConnection.Receive(data);
while (receivedDataLength > 0)
{
try
{
sb.Append(Encoding.UTF8.GetString(data, 0, receivedDataLength));
receivedDataLength = newConnection.Receive(data);
}
catch (SocketException)
{
break;
}
}
return sb.ToString();
}
public static void WriteToSocket(string message, Socket client)
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, SocketFlags.None);
}
}
And here is the simple PHP client, without any error handling etc:
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 9999);
print 'receiving: ' . chr(10);
print socket_read ($socket, 10) . chr(10);
print 'receive end' . chr(10);
$message = str_repeat("Message to sent", 1000);
socket_write($socket, $message, strlen($message));
print 'message sent' . chr(10);
print 'reading fin' . chr(10); // This is printed, but a response is never received
print socket_read ($socket, 10) . chr(10);
print 'fin read!' . chr(10);
socket_shutdown($socket);

You're reading from the socket until all the data has been read - meaning "all the data until the socket is closed". Your PHP client is writing data, but not closing the socket - so the server is waiting forever.
TCP sockets provide a stream of data. There's no concept of "the end of the current message" which is what it looks like you want.
The three ways of handling this are usually:
A message delimiter (e.g. a line break)
A message length prefix (number of bytes in the message just before the message itself)
Use a different connection for each request/response pair
You could potentially use a read with a timeout, and assume that if you haven't seen any more data in the last 5 seconds, you've got the whole message - but that's fragile, inefficient and generally a bad idea.

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();
}
}

C# client socket multiple send and receive

I am using sockets for TCP-IP connection and I would like to establish simple system send-receive from the client side.
Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
int bytes = 0;
String strReceived = "";
int dataAvailable = 0;
while (dataAvailable == 0 || dataAvailable != sck.Available)
{
dataAvailable = sck.Available;
Thread.Sleep(100); // if no new data after 100ms assume transmission finished
}
if (sck.Available > 0)
{
bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
Console.WriteLine("Received from server: " + strReceived);
}
Console.Read();
The problem is that first requests goes throught but the second does not, because socket is not available anymore (socket "Availabe" attribute value is 0). What am I doing wrong? What would be the easiest way to establish multiple send-recieve requests (in order)?
This code works fine for me
private List<Socket> _clients = new List<Socket>();
private Thread _dataReceiveThread;
private bool _isConnected;
private void DataReceive()
{
while (_isConnected)
{
List<Socket> clients = new List<Socket>(_clients);
foreach (Socket client in clients)
{
try
{
if (!client.Connected) continue;
string txt = "";
while (client.Available > 0)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
int byteRec = client.Receive(bytes);
if (byteRec > 0)
txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
}
if (!string.IsNullOrEmpty(txt))
/* TODO: access the text received with "txt" */
}
catch (Exception e)
{
Exception_Handler(e);
}
}
}
}
Just run this code to get started
_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();
Update list box in Cross thread:
This code can be placed in the comment section.
myListBox1.Invoke((Action)(() => { myListBox1.Items.Add(txt) }));
Socket. Available does NOT indicate whether the socket is available, but incoming data is available for reading:
https://msdn.microsoft.com/en-us/library/ee425135.aspx
Your program quits because it checks for a reply (incoming data) immediately after sending a message out. Use a Thread.Sleep before checking for data.
Maybe the message has not even been sent, because Socket.Send just places it in the network interface card's output buffer. When the socket finally sends the message, it will upare the connection state. If it got no reply (on a TCP connection), it will tell you that it is disconnected when you query the state. On UDP it will tell you nothing, because UDP is connectionless.

TCPIP Asynchronous Server connection dropout

i have written(Copied) code for a tcpip server.
We have software that sends a message via TCPIP and expects a return message back to say Receive is Acknowledged. This works fine. But after sending the acknowledgment the connection drops out. I am not sure where in the code this dropout is occurring. So when the next message is sent, there is no connection so it does a rollback and reconnects again and then send the message. So every time i send multiple messages i will keep getting rollback alerts. We will be constantly sending messages all day long. Below is the code :
class Program
{
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
ar.AsyncWaitHandle.WaitOne(100);
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
String s1 = "MSH|^~\\&|BB|NSCCH|MILLENNIUM|BB|20150522080258137||ACK";
String s2 = "|20150522080258137883|P|2.4";//\r\nMSA|AA|Q245548634T287475114";
//String s3 = String.Empty;
String s4 = "MSA|AA|Q245548634T287475114";
//string s5 = "0x02";
int value = Convert.ToInt32("0x1C", 16);
char cc = (char)value;
int value_eob = Convert.ToInt32("0x0b", 16);
char eob = (char)value_eob;
int value_eod = Convert.ToInt32("0x0D", 16);
char eod = (char)value_eod;
int value_eoa = Convert.ToInt32("0x0A", 16);
char eoa = (char)value_eoa;
/*StringBuilder sb1 = new StringBuilder(s5);
sb1.Append(s1);
sb1.Append(s2);
s3 = sb1.ToString();*/
//byte[] s4 = Encoding.ASCII.GetBytes(s3);
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.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));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
//s3 = state.sb.ToString();
// s3 = s1.ToString() + s2.ToString();
if (bytesRead < 1024) //content.IndexOf("<EOF>") > -1)
{
string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
s6.Length, s6);
// Echo the data back to the client.
Send(handler, s6);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
else
{
if (content.Length > 0)
{
string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
s6.Length, s6);
// Echo the data back to the client.
Send(handler, s6);
}
}
// Added code
handler.BeginReceive(state.buffer,0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
private static void Send(Socket handler, 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.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
// handler.Shutdown(SocketShutdown.Both);
// handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(string[] args)
{
StartListening();
return 0;
}
}
}
You have at least two major bugs in your code:
You are assuming that a receive operation will always complete having filled the provided buffer, unless the client has stopped sending data (i.e. there's no more data to be received at the moment). This is often going to be true, but it is not guaranteed and your code will fail spuriously if it makes that assumption.
Once you believe that you have received all of the current transmission from the client, you do not call BeginReceive() again. This renders the connection completely useless from that point forward.
Another possible bug is:
Your code does not correctly partition transmitted data. There does not seem to be any code here that will reliably detect the boundary between two different logical messages in the stream of bytes received. Depending on how quickly data is sent by a client, it is possible that some or all data intended to be part of a later logical message is consumed as part of an earlier logical message.
Unfortunately, there is not enough precise detail provided in your question. The phrase "connection drops out" is non-specific and has no well-defined technical meaning. It could mean you get an error on the socket, or it could simply mean that you never receive any more data, or it could mean something else entirely.
That said, if you mean "never receive any more data", then I would say it is most likely that the #2 bug above is the basic cause of your problem. Of course, the #1 bug can in conjunction with the #2 bug also lead to "never receive any more data".
Without a good, minimal, complete code example that reliably reproduces the problem (please note that for network-related issues, a complete example includes both endpoints of the connection), it's impossible to know for sure all of the bugs in the code example, never mind what the actual problem is. However, I would recommend fixing the above bugs and see if that improves things.
As a general rule, your network code should run like this:
Receive data
Interpret the data, identifying logical message boundary (if any)
If a complete logical message has been received, process it. Be sure to retain any excess data that might have been received, for processing as part of the next logical message.
Continue the above, always initiating a new receive operation after handling the results of the current completed operation, until a receive operation completes with a byte count of zero.
When a zero-byte receive operation completes, complete processing of the data received so far (if there is any not yet processed) and acknowledge the graceful closure of the connection by sending any remaining data (if any) and calling Socket.Shutdown(SocketShutdown.Both), and only then calling Socket.Close() to actually close the socket.

Send binary data and read the values of that using async socket programming

I am trying to send data to a server from my client .the client sends messages to a server ,every message is 36 bytes and in this message every 4 byte is a field and in server part i should be able to detect that field from the message that client sends .Suppose i have this data :
A=21
B=32
c=43
D=55
E=75
F=73
G=12
H=14
M=12
In the client i should send this values as a single message .as you can see my message has 9 field and every field is 4 byte integer and all message is 36 byte.
So in server part when the message is received i should be able to separate the message and find the value of the fields .
In client application i am using this structure to send message to my server :
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Cet the remote IP address
IPAddress ip = IPAddress.Parse(GetIP());
int iPortNo = System.Convert.ToInt16("12345");
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// Connect to the remote host
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
Object objData = ?!!!!;//My message
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
if (m_clientSocket != null)
{
m_clientSocket.Send(byData);
}
Thread.Sleep(4000);
}
}
And in server part i am using this code to receive the data:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
iRx = socketData.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);
System.String szData = new System.String(chars);
MessageBox.Show(szData);
// Continue the waiting for data on the Socket
WaitForData(socketData.m_currentSocket);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
}
}
Here is the other part of my server code :
public void OnClientConnect(IAsyncResult asyn)
{
try
{
// Here we complete/end the BeginAccept() asynchronous call
// by calling EndAccept() - which returns the reference to
// a new Socket object
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
// Let the worker Socket do the further processing for the
// just connected client
WaitForData(m_workerSocket[m_clientCount]);
// Now increment the client count
++m_clientCount;
// Display this client connection as a status message on the GUI
String str = String.Format("Client # {0} connected", m_clientCount);
// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[36];
}
In my form_load of server part i have this code:
ipaddress = GetIP();
// Check the port value
string portStr = "12345";
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
// Start listening...
m_mainSocket.Listen(4);
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
in fact i am trying to implement this link :
http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm
My problem is how can i send my message as a 36 bytes via client and get and separate that from server ?
Every four bytes is a field and i should be able to get this value .
You're doing it wrong. If you want to transmit binary data, do not encode it as a string. There are multiple ways to do this:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Msg
{
public int A, B, C, D, E, F, G, H, M;
}
Then use the Marshal class to get the bytes. This will get you little-endian on the wire data though.
Another method is to use a BinaryWriter. Same thing, little-endian data unless you convert it yourself or use an alternate version of BinaryWriter.
Then, it's much easier to use a NetworkStream, because this class will handle packet fragmentation for you. Here's the sending code using the BinaryWriter method:
using (var stream = new NetworkStream(stocket))
{
var writer = new BinaryWriter(stream);
writer.Write(21);
writer.Write(32);
// etc
}
Same thing on the client side using a NetworkStream and a BinaryReader.
NB: You can use async I/O with NetworkStream using the async/await feature.
Seems like all you need is 2 methods to convert integers to byte-array and vice versa:
byte[] packet = CreateMessage(21,32,43,55,75,73,12,14,12);
//send message
//recv message and get ints back
int[] ints = GetParameters(packet);
....
public byte[] CreateMessage(params int[] parameters)
{
var buf = new byte[parameters.Length * sizeof(int)];
for (int i = 0; i < parameters.Length; i++)
Array.Copy(BitConverter.GetBytes(parameters[i]), 0, buf, i * sizeof(int), sizeof(int));
return buf;
}
public int[] GetParameters(byte[] buf)
{
var ints = new int[buf.Length / sizeof(int)];
for (int i = 0; i < ints.Length; i++)
ints[i] = BitConverter.ToInt32(buf, i * sizeof(int));
return ints;
}

Send text string via TCP?

I just read and tested code of this great article in order to understand TCP Client and Server.
Now I need to do (I hope) really simple thing I need to send some string from TCP Client To TCP Server.
The string is serialized object and it is a XML in fact.
What I don't understand where I have to include this code in TCP Client and also in the TCP server.
TCP Client:
static void Main(string[] args)
{
while (true)
{
String server = "192.168.2.175"; // args[0]; // Server name or IP address
// Convert input String to bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes("1024"); // Encoding.ASCII.GetBytes(args[1]);
// Use port argument if supplied, otherwise default to 8080
int servPort = 1311; // (args.Length == 3) ? Int32.Parse(args[2]) : 8080;//7 ;
TcpClient client = null;
NetworkStream netStream = null;
try
{
// Create socket that is connected to server on specified port
client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending echo string");
netStream = client.GetStream();
// Send the encoded string to the server
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd = 0; // Bytes received in last read
// Receive the same string back from the server
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0)
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception ex)
{
// http://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it
Console.WriteLine(ex.Message);
}
finally
{
if (netStream != null)
netStream.Close();
if (client != null)
client.Close();
}
Thread.Sleep(1000);
}
}
TCP Server
class Program
{
private const int BUFSIZE = 32; // Size of receive buffer
static void Main(string[] args)
{
int servPort = 1311; // (args.Length == 1) ? Int32.Parse(args[0]) : 8080;
TcpListener listener = null;
try
{
// Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
// IPAddress.Any
Console.WriteLine(se.ErrorCode + ": " + se.Message);
//Console.ReadKey();
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
int bytesRcvd; // Received byte count
for (; ; )
{ // Run forever, accepting and servicing connections
// Console.WriteLine(IPAddress.Any);
TcpClient client = null;
NetworkStream netStream = null;
//Console.WriteLine(IPAddress.None);
try
{
client = listener.AcceptTcpClient(); // Get client connection
netStream = client.GetStream();
Console.Write("Handling client - ");
// Receive until client closes connection, indicated by 0 return value
int totalBytesEchoed = 0;
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
// Close the stream and socket. We are done with this client!
netStream.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
Converting my Comments into an answer:
I strongly suggest you use WCF, instead of implementing all the stuff yourself. In WCF, you create the interfaces (Service Contracts) and implementations (Services) and the framework abstracts all the communication / protocol details out.
You can use WCF Duplex to have two-way communications between server and client
The example that you give is a simple 'mirror', where the TCP server sends back to the client the data that it receives from it.
The data that you want to send is in the byteBuffer variable (you are currently sending the text "1024", I believe). So instead of initializing it with "1024", you could initialize it with the XML-serialized data that you want.
On the client side, conversely, instead of echoing the data back to the client, you could simply do whatever you need on the server side with the data, that is your XML object.

Categories