// http://www.codeproject.com/Articles/463947/Working-with-Sockets-in-Csharp // comments say this is problematic, and one recommends c# 3 in a nutshell // one comment recommends his project. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //using System.Windows.For ah maybe won't work 'cos a console application? //using System.Windows; using System.Net; using System.Net.Sockets; //using System.Windows.Controls; using System.Threading; //using System.Windows.Threading; /* after listen, it's on ipv6 * TCP [fe80::9175:a1a2:ed18:2950%45]:4510 [::]:0 LISTENING 33152 [servertest1.vshost.exe] * */ namespace servertest1 { class Program { SocketPermission permission; Socket sListener; IPEndPoint ipEndPoint; Socket handler; static void Main(string[] args) { //http://www.codeproject.com/Articles/463947/Working-with-Sockets-in-Csharp Program p = new Program(); p.startserver(); p.Listen(); Console.ReadLine(); } void startserver() { try { // Creates one SocketPermission object for access restrictions permission = new SocketPermission( NetworkAccess.Accept, // Allowed to accept connections TransportType.Tcp, // Defines transport types "", // The IP addresses of local host SocketPermission.AllPorts // Specifies all ports ); // Listening Socket object sListener = null; // Ensures the code to have permission to access a Socket permission.Demand(); // Resolves a host name to an IPHostEntry instance IPHostEntry ipHost = Dns.GetHostEntry(""); // Gets first IP address associated with a localhost IPAddress ipAddr = ipHost.AddressList[0]; // Creates a network endpoint ipEndPoint = new IPEndPoint(ipAddr, 4510); // Create one Socket object to listen the incoming connection sListener = new Socket( ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); // Associates a Socket with a local endpoint sListener.Bind(ipEndPoint); // tbStatus.Text = "Server started."; // Start_Button.IsEnabled = false; // StartListen_Button.IsEnabled = true; } catch (Exception exc) { Console.WriteLine(exc.ToString()); } } private void Listen() { try { // Places a Socket in a listening state and specifies the maximum // Length of the pending connections queue sListener.Listen(10); // Begins an asynchronous operation to accept an attempt AsyncCallback aCallback = new AsyncCallback(AcceptCallback); sListener.BeginAccept(aCallback, sListener); // tbStatus.Text = "Server is now listening on " + ipEndPoint.Address + " port: " + ipEndPoint.Port; } catch (Exception exc) { Console.WriteLine(exc.ToString()); } } //method public void AcceptCallback(IAsyncResult ar) { Socket listener = null; // A new Socket to handle remote host communication Socket handler = null; try { // Receiving byte array byte[] buffer = new byte[1024]; // Get Listening Socket object listener = (Socket)ar.AsyncState; // Create a new socket handler = listener.EndAccept(ar); // Using the Nagle algorithm handler.NoDelay = false; // Creates one object array for passing data object[] obj = new object[2]; obj[0] = buffer; obj[1] = handler; // Begins to asynchronously receive data handler.BeginReceive( buffer, // An array of type Byt for received data 0, // The zero-based position in the buffer buffer.Length, // The number of bytes to receive SocketFlags.None,// Specifies send and receive behaviors new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate obj // Specifies infomation for receive operation ); // Begins an asynchronous operation to accept an attempt AsyncCallback aCallback = new AsyncCallback(AcceptCallback); listener.BeginAccept(aCallback, listener); } catch (Exception exc) { Console.WriteLine(exc.ToString()); } } public void ReceiveCallback(IAsyncResult ar) { try { // Fetch a user-defined object that contains information object[] obj = new object[2]; obj = (object[])ar.AsyncState; // Received byte array byte[] buffer = (byte[])obj[0]; // A Socket to handle remote host communication. handler = (Socket)obj[1]; // Received message string content = string.Empty; // The number of bytes received. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { content += Encoding.Unicode.GetString(buffer, 0, bytesRead); // If message contains "", finish receiving if (content.IndexOf("") > -1) { // Convert byte array to string string str = content.Substring(0, content.LastIndexOf("")); } else { // Continues to asynchronously receive data byte[] buffernew = new byte[1024]; obj[0] = buffernew; obj[1] = handler; handler.BeginReceive(buffernew, 0, buffernew.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), obj); } } } catch (Exception exc) { Console.WriteLine(exc.ToString()); } } } //class } //namespace