Home
Manage Your Code
Snippet: network socket server (C#)
Title: network socket server Language: C#
Description: This is a server using a typical socket connection. Also look at the "network socket client" snippet. Views: 130
Author: Alexandru Ionescu Date Added: 1/27/2008
Copy Code  
1try {
2			IPAddress ipAd = IPAddress.Parse("192.168.0.2"); //use local m/c IP address, and use the same in the client

3			TcpListener myList=new TcpListener(ipAd,8001);
4
5			myList.Start();
6
7			Console.WriteLine("The server is running at port 8001...");	
8			Console.WriteLine("The local End point is  :" + myList.LocalEndpoint );
9			Console.WriteLine("Waiting for a connection.....");
10
11			Socket s=myList.AcceptSocket();
12			Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);
13
14			byte[] b=new byte[100];
15			int k=s.Receive(b);
16			Console.WriteLine("Recieved...");
17			for (int i=0;i<k;i++)
18				Console.Write(Convert.ToChar(b[i]));
19
20			ASCIIEncoding asen=new ASCIIEncoding();
21			s.Send(asen.GetBytes("The string was recieved by the server."));
22			Console.WriteLine("\\nSent Acknowledgement");
23
24			s.Close();
25			myList.Stop();
26
27}
28
29catch (Exception e) {
30			Console.WriteLine("Error..... " + e.StackTrace);
31	            }	
32	
Notes
Also look at the "network socket client" snippet.