本实例详述了C#实现Socket通信的⽅法,
参考知新文学视频教程
具体实现步骤如下:
1、打开VS2019新建两个控制台应⽤程序:
ConsoleTestApplication_socketServer和ConsoleTestApplication_socketClient。
2、在ConsoleTestApplication_socketClient中写入下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleTestApplication_socketClient
{
class Program
{
static Socket clientSocket;
static void Main(string[] args)
{
//将⽹络端点表⽰:IP地址&端⼝ ⽤Socket侦听绑定
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("*.*.*.*"), 3001); //填写本地电脑的IP或者其他路由器能拼通的电脑的IP,如果是其他电脑IP,则需将ConsoleTestApplication_socketServer⼯程放在对方的电脑上运行,客户端侦听。
clientSocket = new Socket(ipep.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
//将Socket连接到服务器
try
{
clientSocket.Connect(ipep);
String outBufferStr;
Byte[] outBuffer = new Byte[1024];
Byte[] inBuffer = new Byte[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、在ConsoleTestApplication_socketServer中写下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleTestApplication_socketServer
{
class Program
{
static Socket serverSocket;
static Socket clientSocket;
static Thread thread;
static void Main(string[] args)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 3001);
serverSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ipep);
serverSocket.Listen(10);
while (true)
{
clientSocket = serverSocket.Accept();
thread = new Thread(new ThreadStart(doWork));
thread.Start();
}
}
private static void doWork()
{
Socket s = clientSocket;//客户端信息
IPEndPoint ipEndPoint = (IPEndPoint)s.RemoteEndPoint;
String address = ipEndPoint.Address.ToString();
String port = ipEndPoint.Port.ToString();
Console.WriteLine(address + ":" + port + " 链接成功!");
Byte[] inBuffer = new Byte[1024];
Byte[] outBuffer = new Byte[1024];
String inBufferStr;
String outBufferStr;try
{
while (true)
{
s.Receive(inBuffer, 1024, SocketFlags.None);//如果接收的消息为Null 则阻塞当前循环
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.先运⾏服务端:ConsoleTestApplication_socketServer,
后运⾏客户端:ConsoleTestApplication_socketClient通信成功了。
本实例用通熟易懂的方式,采用最基础的方式实现Socket通讯交互,
您可以根据⾃⾝的需求场景做进⼀步个性化功能的研发和深入研究。