C # Socket simple example (server to communicate with clients)

This example is simply realized how Socket connection-oriented class for communication.

Note: The purpose of this example is for illustrative purposes only thinking about writing programs with the socket, rather than using the actual program project. In this case, in fact, there are many issues remain unresolved, such as the message boundary issue, the port number is occupied, resolve problems such as message command. .

Here is the code of both programs, ( both programs are console programs )

(Server) complete code for starting the server as follows:

 

The introduction of the namespace:

using System.Net.Sockets;  
using System.Net;
using System.Threading;

 

The complete code is as follows:

Copy the code
namespace SocketServer  
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885; //端口
static Socket serverSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = newThe Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.bind ( new new the IPEndPoint (IP, myProt)); // bind the IP address: port
serverSocket.Listen ( 10 ); // set up to 10 queued connection request
Console.WriteLine ( " start listening {0} success " , serverSocket.LocalEndPoint.ToString ());
// send data Clientsoket
the Thread myThread = new new the Thread (ListenClientConnect);
myThread.Start ();
Console.ReadLine ( );
}

/// <Summary> /// listen for client connection ///

</summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}

/// <summary>
/// 接收消息
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Copy the code

These are the server (server) of the complete code.

 

The client (Client) complete code is as follows:

 

The introduction of the namespace:

using System.Net;  
using System.Net.Sockets;
using System.Threading;

 

Complete code:

Copy the code
namespace SocketClient  
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(newIPEndPoint (ip, 8885 )); // server IP and port
Console.WriteLine ( " connect to the server successfully " );
}
the catch
{
Console.WriteLine ( " Connection to server failed, press the Enter key to exit! " );
Return ;
}
// clientSocket receive data via int receiveLength clientSocket.Receive = (Result); Console.WriteLine ( " receiving server message: {0} " , Encoding.ASCII.GetString (Result, 0 , receiveLength)); // send via clientSocket data for



(int i = 0; i < 10; i++)
{
try
{
Thread.Sleep(1000); //等待1秒钟
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close ();
BREAK ;
}
}
Console.WriteLine ( " transmission is completed, press the Enter key to exit " );
Console.ReadLine ();
}
}
}
Copy the code

 

After successful compilation, run the server (server), and then run the client (client) can achieve the effect of communication.

Results as shown:

The procedure has been tested by a local area network. (192.168.XX)

If the compilation fails, to the following address to download the project files:

http://files.cnblogs.com/andrew-blog/SocketServerAndClient.rar

http://www.cnblogs.com/andrew-blog/archive/2011/12/02/CSharp_Socket.html

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/09/16/2688007.html

Guess you like

Origin blog.csdn.net/weixin_34303897/article/details/93495271