C#实现Socket通信的解决方法
本文以实例详述了C#实现Socket通信的解决方法,具体实现步骤如下:
1、首先打开VS新建两个控制台应用程序:
ConsoleApplication_socketServer和ConsoleApplication_socketClient。
2、在ConsoleApplication_socketClient中输入以下代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.Net.Sockets;
namespaceConsoleApplication_socketClient
{
classProgram
{
staticSocketclientSocket;
staticvoidMain(string[]args)
{
//将网络端点表示为IP地址和端口用于socket侦听时绑定
IPEndPointipep=newIPEndPoint(IPAddress.Parse("*.*.*.*"),3001);//填写自己电脑的IP或者其他电脑的IP,如果是其他电脑IP的话需将ConsoleApplication_socketServer工程放在对应的电脑上。
clientSocket=newSocket(ipep.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
//将Socket连接到服务器
try
{
clientSocket.Connect(ipep);
StringoutBufferStr;
Byte[]outBuffer=newByte[1024];
Byte[]inBuffer=newByte[1024];
while(true)
{
//发送消息
outBufferStr=Console.ReadLine();
outBuffer=Encoding.ASCII.GetBytes(outBufferStr);
clientSocket.Send(outBuffer,outBuffer.Length,SocketFlags.None);
//接收服务器端信息
clientSocket.Receive(inBuffer,1024,SocketFlags.None);//如果接收的消息为空阻塞当前循环
Console.WriteLine("服务器说:");
Console.WriteLine(Encoding.ASCII.GetString(inBuffer));
}
}
catch
{
Console.WriteLine("服务未开启!");
Console.ReadLine();
}
}
}
}
3、在ConsoleApplication_socketServer中输入以下代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
namespaceConsoleApplication_socketServer
{
classProgram
{
staticSocketserverSocket;
staticSocketclientSocket;
staticThreadthread;
staticvoidMain(string[]args)
{
IPEndPointipep=newIPEndPoint(IPAddress.Any,3001);
serverSocket=newSocket(ipep.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
serverSocket.Bind(ipep);
serverSocket.Listen(10);
while(true)
{
clientSocket=serverSocket.Accept();
thread=newThread(newThreadStart(doWork));
thread.Start();
}
}
privatestaticvoiddoWork()
{
Sockets=clientSocket;//客户端信息
IPEndPointipEndPoint=(IPEndPoint)s.RemoteEndPoint;
Stringaddress=ipEndPoint.Address.ToString();
Stringport=ipEndPoint.Port.ToString();
Console.WriteLine(address+":"+port+"连接过来了");
Byte[]inBuffer=newByte[1024];
Byte[]outBuffer=newByte[1024];
StringinBufferStr;
StringoutBufferStr;
try
{
while(true)
{
s.Receive(inBuffer,1024,SocketFlags.None);//如果接收的消息为空阻塞当前循环
inBufferStr=Encoding.ASCII.GetString(inBuffer);
Console.WriteLine(address+":"+port+"说:");
Console.WriteLine(inBufferStr);
outBufferStr=Console.ReadLine();
outBuffer=Encoding.ASCII.GetBytes(outBufferStr);
s.Send(outBuffer,outBuffer.Length,SocketFlags.None);
}
}
catch
{
Console.WriteLine("客户端已关闭!");
}
}
}
}
4、先运行ConsoleApplication_socketServer,后运行ConsoleApplication_socketClient就可以通信了。
本例给出了基本的实现代码,读者可以根据自身的需求进一步完成个性化功能。