WPF基本的客户端和服务端TCP通信代码

时间: 2023-10-31 14:05:37 浏览: 53
以下是一个简单的 WPF 客户端和服务端 TCP 通信的示例代码: 服务端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Server { class Program { static void Main(string[] args) { TcpListener server = null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also use server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a ASCII string. data = Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } } ``` 客户端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Client { class Program { static void Main(string[] args) { string server = "127.0.0.1"; int port = 13000; try { TcpClient client = new TcpClient(server, port); // Translate the passed message into ASCII and store it as a Byte array. string message = "Hello, server!"; byte[] data = Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new byte[256]; // String to store the response ASCII representation. string responseData = string.Empty; // Read the first batch of the TcpServer response bytes. int bytes = stream.Read(data, 0, data.Length); responseData = Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } } ``` 这里使用了 .NET Framework 自带的 TCP 相关类,服务端使用 `TcpListener` 监听客户端连接,客户端使用 `TcpClient` 连接服务器,使用 `NetworkStream` 进行数据通信。注意修改 IP 地址和端口号以适应您的需求。

相关推荐

最新推荐

recommend-type

C# WPF上位机实现和下位机TCP通讯的方法

主要介绍了C# WPF上位机实现和下位机TCP通讯的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

在WPF中动态加载XAML中的控件实例代码

主要介绍了在WPF中动态加载XAML中的控件,实例分析了WPF中针对XAML中控件的动态调用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
recommend-type

WPF InkCanvas绘制矩形和椭圆

主要为大家详细介绍了WPF InkCanvas绘制矩形和椭圆,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

WPF自定义控件和样式之自定义按钮(Button)

接触WPF也有两个多月了,有了一定的理论基础和项目经验,现在打算写一个系列,做出来一个WPF的控件库。下面这篇文章主要给大家介绍了关于WPF自定义控件和样式之自定义按钮(Button)的相关资料,需要的朋友可以参考...
recommend-type

C# WPF新手入门之串口Modbus通讯

C#WPF制作的上位机和SmartGas气体分析模块通讯 需要完整项目文件的可在我的资源中另外下载
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

机器学习怎么将excel转为csv文件

机器学习是一种利用计算机算法和统计数据的方法来训练计算机来进行自动学习的科学,无法直接将excel文件转为csv文件。但是可以使用Python编程语言来读取Excel文件内容并将其保存为CSV文件。您可以使用Pandas库来读取Excel文件,并使用to_csv()函数将其保存为CSV格式。以下是代码示例: ```python import pandas as pd # 读取 Excel 文件 excel_data = pd.read_excel('example.xlsx') # 将数据保存为 CSV 文件 excel_data.to_csv('example.csv', index=
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。