使用winfrom编写一个TCP client程序
时间: 2024-05-14 12:12:42 浏览: 14
以下是一个简单的TCP客户端程序,使用C#和WinForm编写。
1. 创建一个新的WinForm应用程序项目。
2. 添加一个TextBox控件,用于输入服务器的IP地址。
3. 添加一个TextBox控件,用于输入服务器的端口号。
4. 添加一个Button控件,用于连接服务器。
5. 添加一个TextBox控件,用于显示从服务器接收到的消息。
6. 添加一个TextBox控件,用于输入要发送到服务器的消息。
7. 添加一个Button控件,用于发送消息到服务器。
以下是代码实现:
```csharp
using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace TcpClientDemo
{
public partial class Form1 : Form
{
private TcpClient client;
private NetworkStream stream;
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
// 获取服务器的IP地址和端口号
string ipAddress = txtIpAddress.Text;
int port = int.Parse(txtPort.Text);
// 创建TCP客户端
client = new TcpClient(ipAddress, port);
stream = client.GetStream();
// 开始接收来自服务器的消息
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
txtReceived.Text = message;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
// 获取要发送的消息
string message = txtMessage.Text;
// 发送消息到服务器
byte[] buffer = Encoding.ASCII.GetBytes(message);
stream.Write(buffer, 0, buffer.Length);
// 清空输入框
txtMessage.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
```
在代码中,我们首先在btnConnect_Click事件处理程序中创建TCP客户端,并获取来自服务器的消息。然后,在btnSend_Click事件处理程序中将消息发送到服务器。
请注意,我们需要使用try-catch块来捕获可能发生的异常,并使用MessageBox.Show方法将错误消息显示给用户。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)