Click here to Skip to main content
15,905,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

so I'm trying to figure out the "proper" and most efficient way to send multiple messages on a socket connection. I've read and tested all the code samples here: Socket Code Examples. But they all do a single send and receive. I've also read some posts that give clues how to do multiple messages namely(asynchronous server socket C# continue sending messages) but when I remove the handler.Shutdown and handler.Close the client never ends the receive.

So I'm wondering if this is really something that's not supposed to be done on a single connection. Can anybody give direction on this or is just better to open connection, send/receive, close the connection, repeat.


What I have tried:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;

namespace AsyncTestServer
	public class AsynchronousSocketListener
		// Thread signal.  
		public static ManualResetEvent allDone = new ManualResetEvent(false);

		public AsynchronousSocketListener()

		public static void StartListening()
			// Establish the local endpoint for the socket.  
			// The DNS name of the computer  
			// running the listener is "".  
			//IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
			//IPAddress ipAddress = ipHostInfo.AddressList[0];
			IPAddress ipAddress = IPAddress.Parse("");
			IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8765);

			// Create a TCP/IP socket.  
			Socket listener = new Socket(ipAddress.AddressFamily,
				SocketType.Stream, ProtocolType.Tcp);

			// Bind the socket to the local endpoint and listen for incoming connections.  

				while (true)
					// Set the event to nonsignaled state.  

					// Start an asynchronous socket to listen for connections.  
					Console.WriteLine("Waiting for a connection...");
						new AsyncCallback(AcceptCallback),

					// Wait until a connection is made before continuing.  

			catch (Exception e)

			Console.WriteLine("\nPress ENTER to continue...");


		public static void AcceptCallback(IAsyncResult ar)
			// Signal the main thread to continue.  

			// 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;

			// 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., 0, bytesRead));

				// Check for end-of-file tag. If it is not there, read   
				// more data.  
				content =;
				if (content.IndexOf("</request>") > -1)
					// 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);

					// Echo the data back to the client.  
					Send(handler, content + "-received");

					// All data received. Get next message.;
					handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
					// Not all data received. Get more.  
					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)
				// 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);

			catch (Exception e)

		public static int Main(String[] args)
			return 0;
Updated 11-Jun-18 8:52am
Kevin Marois 11-Jun-18 16:42pm    
I suggest you take a look at SignalR. It autoamtically uses different methods, including Web Sockets, but it nicely wraps up all the work for you. And you can send any kind of message you want. And, to add to that, it's REALLY simple to set up & use.
DBLWizard 11-Jun-18 16:49pm    
That's not an answer to my question, though thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900