TCP/IP网络通信-数据传输
2017-02-22 11:53 Evan.Pei 阅读(342) 评论(0) 编辑 收藏 举报1.通过网络IP实现数据的传输。
2.服务器端代码 【 服务端主要通过Socket类来创建一个监听等待客户端连接,服务端发送用send方法,接收用Receive方法】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | using System.Net.Sockets; using System.IO; using System.Net; private void Waek_Load( object sender, EventArgs e) { //打开Listener开始监听 Thread thrListener = new Thread( new ThreadStart(Listen)); thrListener.Start(); } //监听数据 private static Encoding encode = Encoding.Default; private void Listen() { Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind( new IPEndPoint(IPAddress.Any, 10000)); //获取服务器IP,和设置一个端口号 listenSocket.Listen(100); Socket acceptSocket = listenSocket.Accept(); //一直等待,直到有客户端连入 while ( true ) //客户端连入才会到循环。 { try { string receiveData = Receive(acceptSocket, 5000); //5 seconds timeout. if (receiveData != "" ) { //接收客户端发送的数据 Invoke((EventHandler) delegate { label5.Text = receiveData; }); //给客户端回复数据 acceptSocket.Send(encode.GetBytes( "ok+00 00 01 02 03" )); } } catch (Exception ex) { } } } /// <summary> /// 接收数据 /// </summary> /// <param name="socket"></param> /// <param name="timeout"></param> /// <returns></returns> private static string Receive(Socket socket, int timeout) { string result = string .Empty; socket.ReceiveTimeout = timeout; List< byte > data = new List< byte >(); byte [] buffer = new byte [1024]; int length = 0; try { while ((length = socket.Receive(buffer)) > 0) { for ( int j = 0; j < length; j++) { data.Add(buffer[j]); } if (length < buffer.Length) { break ; } } } catch { } if (data.Count > 0) { result = encode.GetString(data.ToArray(), 0, data.Count); } return result; } /// <summary> /// 销毁Socket对象 /// </summary> /// <param name="socket"></param> private static void DestroySocket(Socket socket) { if (socket.Connected) { socket.Shutdown(SocketShutdown.Both); } socket.Close(); } |
3.客户端代码【客户端端主要通过TcpClient类去连接服务端 将连接好的对象赋值给NetworkStream类来发送和接收数据 接收用Read()方法,发送用Wirte()方法】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | NetworkStream ntwStream = null ; TcpClient tcpClient = null ; private void Form1_Load( object sender, EventArgs e) { tcpClient = new TcpClient(); tcpClient.Connect(System.Net.IPAddress.Parse( "172.17.100.97" ), 10000); //设置链接到的服务器地址及端口 ntwStream = tcpClient.GetStream(); //开始链接 // 打印连接到的服务端信息 label1.Text = string .Format( "已经成功与客户端建立连接!{0} --> {1}" , tcpClient.Client.LocalEndPoint, tcpClient.Client.RemoteEndPoint); //启动接收服务器发送来的数据 Thread thrListener = new Thread( new ThreadStart(Listen)); thrListener.Start(); } //监听数据 private static Encoding encode = Encoding.Default; private void Listen() { while ( true ) { try { byte [] buffer = new byte [1024]; int receiveData = ntwStream.Read(buffer, 0, buffer.Length); int length = 0; if (receiveData != 0) { List< byte > data = new List< byte >(); length = buffer.Length; for ( int j = 0; j < length; j++) { data.Add(buffer[j]); } string result = encode.GetString(data.ToArray(), 0, data.Count); Invoke((EventHandler) delegate { textBox2.Text = result.ToString(); }); } } catch (Exception ex) { } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //客户端往服务器写入数据 private void button1_Click( object sender, EventArgs e) { if (ntwStream.CanWrite) { Byte[] bytSend = Encoding.UTF8.GetBytes(textBox1.Text); ntwStream.Write(bytSend, 0, bytSend.Length); } else { Console.WriteLine( "无法写入数据流" ); ntwStream.Close(); tcpClient.Close(); return ; } } |
//截图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构