详解C# Socket简单例子(服务器与客户端通信)

这个例子只是简单实现了如何使用 Socket 类实现面向连接的通信。

注意:此例子的目的只是为了说明用套接字写程序的大概思路,而不是实际项目中的使用程序。在这个例子中,实际上还有很多问题没有解决,如消息边界问题、端口号是否被占用、消息命令的解析问题等。。

下面是两个程序的代码,(两个程序均为控制台程序)

先发服务端的(Server)完整代码如下:

引入命名空间:

using System.Net.Sockets;

using SystemNet;

using SystemThreading;

完整代码如下:

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 = IPAddressParse("1");

serverSocket = new Socket(AddressFamilyInterNetwork, SocketTypeStream, ProtocolTypeTcp);

serverSocketBind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口

serverSocketListen(10); //设定最多10个排队连接请求

ConsoleWriteLine("启动监听{0}成功", serverSocketLocalEndPointToString());

//通过Clientsoket发送数据

Thread myThread = new Thread(ListenClientConnect);

myThreadStart();

ConsoleReadLine();

}

/// <summary>

/// 监听客户端连接

/// </summary>

private static void ListenClientConnect()

{

while (true)

{

Socket clientSocket = serverSocketAccept();

clientSocketSend(EncodingASCIIGetBytes("Server Say Hello"));

Thread receiveThread = new Thread(ReceiveMessage);

receiveThreadStart(clientSocket);

}

}

/// <summary>

/// 接收消息

/// </summary>

/// <param name="clientSocket"></param>

private static void ReceiveMessage(object clientSocket)

{

Socket myClientSocket = (Socket)clientSocket;

while (true)

{

try

{

//通过clientSocket接收数据

int receiveNumber = myClientSocketReceive(result);

ConsoleWriteLine("接收客户端{0}消息{1}", myClientSocketRemoteEndPointToString(), EncodingASCIIGetString(result, 0, receiveNumber));

}

catch(Exception ex)

{

ConsoleWriteLine(exMessage);

myClientSocketShutdown(SocketShutdownBoth);

myClientSocketClose();

break;

}

}

}

}

}

以上是服务端(server)的完整代码。

客户端(Client)的完整代码如下:

引入命名空间:

using SystemNet;

using SystemNetSockets;

using SystemThreading;

完整代码:

namespace SocketClient

{

class Program

{

private static byte[] result = new byte[1024];

static void Main(string[] args)

{

//设定服务器IP地址

IPAddress ip = IPAddressParse("1");

Socket clientSocket = new Socket(AddressFamilyInterNetwork, SocketTypeStream, ProtocolTypeTcp);

try

{

clientSocketConnect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口

ConsoleWriteLine("连接服务器成功");

}

catch

{

ConsoleWriteLine("连接服务器失败,请按回车键退出!");

return;

}

//通过clientSocket接收数据

int receiveLength = clientSocketReceive(result);

ConsoleWriteLine("接收服务器消息:{0}",EncodingASCIIGetString(result,0,receiveLength));

//通过 clientSocket 发送数据

for (int i = 0; i < 10; i++)

{

try

{

ThreadSleep(1000); //等待1秒钟

string sendMessage = "client send Message Hellp" + DateTimeNow;

clientSocketSend(EncodingASCIIGetBytes(sendMessage));

ConsoleWriteLine("向服务器发送消息:{0}" + sendMessage);

}

catch

{

clientSocketShutdown(SocketShutdownBoth);

clientSocketClose();

break;

}

}

ConsoleWriteLine("发送完毕,按回车键退出");

ConsoleReadLine();

}

}

}

编译成功后,先运行 服务端(server),再运行客户端(client)即可达到通信效果。

效果如下图:

该程序已在局域网测试通过。(192.168.X.X)

若编译失败,可到下面的地址下载项目文件:demo

以上是 详解C# Socket简单例子(服务器与客户端通信) 的全部内容, 来源链接: utcz.com/z/320119.html

回到顶部