Socket TCP通讯Demo 三:Socket TCP怎样来使用?
Socket TCP应用--C# winForm
首先:创建两个通讯window窗体应用程序 服务器(Server) 和客户端(Client) 名称随意
服务器代码:
1.启动监听功能
//创建一个Socket对象 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //设置指定的端口号和服务器的IP地址 IPAddress ip = IPAddress.Parse(txt_IP.Text); IPEndPoint endpoint = new IPEndPoint(ip, Convert.ToInt32(txt_Port.Text)); //绑定IPEndPoint socketWatch.Bind(endpoint); ShowMsg("监听成功"); //设置监听20个客户端服务器: socketWatch.Listen(20); //创建线程用来监听; //线程创建方法:Thread th = new Thread(Listen); //其中listen为方法名 即实例化 Thread th = new Thread(Listen); th.IsBackground = true; th.Start(socketWatch); //Start里面的参数 是线程方法的参数
2.等待客户端的连接 并且创建与之通信用的Socket
Socket socketWatch = o as Socket; while (true) { try { //创建一个新的用于与客户端进行通信的socket对象 socketSend = socketWatch.Accept(); ipAddress = socketSend.RemoteEndPoint.ToString(); //获得客户端的ip地址和端口号 ipAddress格式例如:127.0.0.1:50000 dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend); //192.168...连接成功 ShowMsg(ipAddress + ":" + "连接成功"); //创建一个新的线程,用来不停的接收客户端发送过来的消息 Thread th = new Thread(Recive); th.IsBackground = true; th.Start(socketSend); } catch { } }
3.接收消息
void Recive(object o) { Socket socketSend = o as Socket; while (true) { byte[] buffer = new byte[1024 * 1024 * 10]; //设置缓存大小 int r = socketSend.Receive(buffer); //实际接收到的有效字节数 if (r == 0) { break; } if (buffer[0] == 0) //表示收到的是数据 { string s = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(socketSend.RemoteEndPoint + ":" + s); } else if (buffer[0] == 1) //表示收到的是文件 { string filePath = ""; SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "保存文件"; sfd.InitialDirectory = @"C:\Users\Administrator\Desktop"; sfd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|音乐文件|*.mp3|所有文件|*.*"; while (true) { sfd.ShowDialog(this); filePath = sfd.FileName; if (string.IsNullOrEmpty(filePath)) { continue; } else { break; } } //保存接收的文件 using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { fsWrite.Write(buffer, 1, r - 1); } ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功"); } else if (buffer[0] == 2) { Popping(); } } }
4.发送消息到客户端
string str = txt_Message.Text; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); //将字符串转成二进制格式字节 List<byte> list = new List<byte>(); list.Add(0); //让客户端知道现在发送的文字 list.AddRange(buffer); byte[] newBuffer = list.ToArray(); dicSocket[ipAddress].Send(newBuffer); //传输字符串到客户端 txt_Message.Text = "";
5.关闭监听进程
socketSend.Close();
客户端代码:
1.连接到服务器
//创建通信的Socket socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(txt_IP.Text); IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_Port.Text)); //连接到对应的IP地址和端口号 socketSend.Connect(point); ShowMsg("连接成功"); Thread threadClient = new Thread(Recive); threadClient.IsBackground = true; //设置为后台线程 threadClient.Start();
2.用于接收服务器传来的消息
while (true) { byte[] buffer = new byte[1024 * 1024 * 10]; //设置缓存大小 int r = socketSend.Receive(buffer); //实际接收到的有效字节数 if (r == 0) { break; } if (buffer[0] == 0) //表示收到的是数据 { string s = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(socketSend.RemoteEndPoint + ":" + s); } else if (buffer[0] == 1) //表示收到的是文件 { string filePath = ""; SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "保存文件"; sfd.InitialDirectory = @"C:\Users\Administrator\Desktop"; sfd.Filter = "文本文件|*.txt|图片文件|*.jpg|视频文件|*.avi|音乐文件|*.mp3|所有文件|*.*"; while (true) { sfd.ShowDialog(this); filePath = sfd.FileName; if (string.IsNullOrEmpty(filePath)) { continue; } else { break; } } //保存接收的文件 using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { fsWrite.Write(buffer, 1, r - 1); } ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功"); } else if (buffer[0] == 2) { Popping(); } }
3.发送消息到服务器
string str = txt_SendMessage.Text.Trim(); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); //转换成序列形式 List<byte> list = new List<byte>(); list.Add(0); //让服务端知道现在发送的文字 list.AddRange(buffer); byte[] newBuffer = list.ToArray(); socketSend.Send(newBuffer); txt_SendMessage.Text = ""; //清空输入框
4.关闭线程
socketSend.Shutdown(SocketShutdown.Both);
socketSend.Close();
链接demo:https://pan.baidu.com/s/1dhAYDOoNGRsud970-KFDyA
提取码:yh4i