Socket简单通信
Socket通信流程图

C# Socket代码实现
服务端:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ServerManager
{
class Program
{
static Socket server; //服务器
static void Main(string[] args)
{
int port = 8885; //端口
IPAddress ip = IPAddress.Any; // 侦听所有网络客户接口的客活动
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port);
server.Bind(new IPEndPoint(ip, port));//绑定IP地址和端口号
server.Listen(10); //设定最多有10个排队连接请求
Console.WriteLine("建立连接");
Socket socket = server.Accept(); //挂起,一直等客户端连接
byte[] receive = new byte[1024];
int length = socket.Receive(receive); // length 接收字节数组长度
Console.WriteLine("接收到消息:" + Encoding.ASCII.GetString(receive,0,length));
byte[] send = Encoding.ASCII.GetBytes("Success receive the message,send the back the message");
socket.Send(send);
Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(send));
socket.Close();
server.Close();
Console.ReadLine();
}
}
}
客户端:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ClientManager
{
class Program
{
static Socket client;
static void Main(string[] args)
{
int port = 8885;
IPAddress ip = IPAddress.Parse("127.0.0.1"); //将IP地址字符串转换成IPAddress实例
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port);// 用指定的ip和端口号初始化IPEndPoint实例
client.Connect(endPoint); //与远程主机建立连接
Console.WriteLine("开始发送消息");
byte[] message = Encoding.ASCII.GetBytes("Connect the Server"); //通信时实际发送的是字节数组,所以要将发送消息转换字节
client.Send(message);
Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(message));
byte[] receive = new byte[1024];
int length = client.Receive(receive); // length 接收字节数组长度
Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive,0,length));
client.Close(); //关闭连接
Console.ReadLine();
}
}
}


浙公网安备 33010602011771号