c# socket初学小demo
转载于:博主文章
1.客户端:
点击查看代码
static Socket ClientSocket;
public void Send()
{
String IP = "127.0.0.1";
int port = 8885;
IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
ClientSocket.Connect(endPoint); //与远程主机建立连接
Console.WriteLine("开始发送消息");
string send=Console.ReadLine();
byte[] message = Encoding.UTF8.GetBytes(send); //通信时实际发送的是字节数组,所以要将发送消息转换字节
ClientSocket.Send(message);
Console.WriteLine("发送消息为:" + send);
byte[] receive = new byte[1024];
int length = ClientSocket.Receive(receive); // length 接收字节数组长度
Console.WriteLine("接收消息为:" + Encoding.UTF8.GetString(receive));
ClientSocket.Close(); //关闭连接
}
2.服务端
点击查看代码
static Socket ReceiveSocket;
public void Receive()
{
int port = 8885;
IPAddress ip = IPAddress.Any; // 侦听所有网络客户接口的客活动
ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 <br>
//ReceiveSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); //有关套接字设置
IPEndPoint endPoint = new IPEndPoint(ip, port);
ReceiveSocket.Bind(new IPEndPoint(ip, port)); //绑定IP地址和端口号
ReceiveSocket.Listen(10); //设定最多有10个排队连接请求
Console.WriteLine("建立连接");
Socket socket = ReceiveSocket.Accept();
byte[] receive = new byte[1024];
socket.Receive(receive);
Console.WriteLine("接收到消息:" + Encoding.UTF8.GetString(receive));
string test=Console.ReadLine();
byte[] send = Encoding.UTF8.GetBytes(test);
socket.Send(send);
//ASCII
Console.WriteLine("发送消息为:" + Encoding.UTF8.GetString(send));
}
越是无知的人越是觉得自己无所不知(之前的自己)
越是学习的人越是觉得自己会的太少了(现在的自己)
共勉