Socket编程服务端与客户端
服务端:
class Program
{
static void Main(string[] args)
{
//1. 创建socket
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2. 绑定IP和端口号
IPAddress ipaddress = new IPAddress(new byte[]{127,0,0,1});
EndPoint point = new IPEndPOint(ipaddress, 9600);//对IP+端口做了封装的类
tcpServer.Bind(point);
//3. 开始监听(等待客户端连接)
tcpServer.Listen(100);
Console.WriteLine(“开始监听”);
Socket clientSocket = tcpServer.Accept();//暂停当前线程,直到一个客户端连接过来,之后进行下面的代码
Console.WriteLine(“一个客户端链接过来了”);
//4. 使用返回的socket跟客户端做通信
string message = “欢迎!”;
byte[] data = Encoding.UTF8.GetBytes(message);//
clientSocket.Send(data);
Console.WriteLine(“向客户端发送消息” + message);
byte[] data2 = new byte[1024];//创建以一个字节数组当作容器,承接客户端发送过来的数据
int length = clientSocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0, length);//转化为字符串
Console.WriteLine(“接收到一个客户端发送过来的消息”);
Console.ReadKey();
}
}
客户端:
class Program { static void Main(string[] args) { //1. 创建socket Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2. 发起建立连接的请求 IPAddress iPAddress = IPAddress.Parse("192.168.152.1"); EndPoint point = new IPEndPoint(iPAddress,9600); tcpClient.Connect(point); //3. 接收服务器发来的消息 byte[] data = new byte[1024]; int length = tcpClient.Receive(data); string message = Encoding.UTF8.GetString(data,0,length);//只把接收到的数据做转化 Console.WriteLine(message); //4. 向服务器端发送消息 string message2 = Console.ReadLine(); tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串转化成字节数组发送到服务器端 Console.ReadKey(); } }