写一个C# 带样式Socket点对点通信,要求界面上有连接按钮,断开按钮,发送按钮,两个RichTextBox控件,端口号要固定
时间: 2023-06-17 11:03:38 浏览: 181
以下是一个简单的 C# 带样式 Socket 点对点通信程序,界面上包含连接按钮、断开按钮、发送按钮和两个 RichTextBox 控件,并且端口号固定为 8888:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SocketDemo
{
public partial class Form1 : Form
{
private Socket clientSocket;
private Thread receiveThread;
public Form1()
{
InitializeComponent();
}
private void ConnectButton_Click(object sender, EventArgs e)
{
try
{
// 创建客户端 Socket
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接服务器
clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 8888);
// 启动接收线程
receiveThread = new Thread(ReceiveMessage);
receiveThread.Start();
// 更新界面状态
ConnectButton.Enabled = false;
DisconnectButton.Enabled = true;
SendMessageButton.Enabled = true;
MessageBox.Show("连接成功!");
}
catch (Exception ex)
{
MessageBox.Show("连接失败:" + ex.Message);
}
}
private void DisconnectButton_Click(object sender, EventArgs e)
{
try
{
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
// 停止接收线程
receiveThread.Abort();
// 更新界面状态
ConnectButton.Enabled = true;
DisconnectButton.Enabled = false;
SendMessageButton.Enabled = false;
MessageBox.Show("已断开连接!");
}
catch (Exception ex)
{
MessageBox.Show("断开连接失败:" + ex.Message);
}
}
private void SendMessageButton_Click(object sender, EventArgs e)
{
try
{
// 发送消息
byte[] buffer = Encoding.UTF8.GetBytes(MessageTextBox.Text);
clientSocket.Send(buffer);
// 清空输入框
MessageTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show("发送消息失败:" + ex.Message);
}
}
private void ReceiveMessage()
{
try
{
while (true)
{
// 接收消息
byte[] buffer = new byte[1024];
int bufferSize = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, bufferSize);
// 显示消息
if (InvokeRequired)
{
Invoke(new Action(() =>
{
ReceiveRichTextBox.AppendText(message);
ReceiveRichTextBox.ScrollToCaret();
}));
}
else
{
ReceiveRichTextBox.AppendText(message);
ReceiveRichTextBox.ScrollToCaret();
}
}
}
catch (Exception ex)
{
MessageBox.Show("接收消息失败:" + ex.Message);
}
}
}
}
```
其中,ConnectButton_Click 方法用于连接服务器,DisconnectButton_Click 方法用于断开连接,SendMessageButton_Click 方法用于发送消息,ReceiveMessage 方法用于接收消息并显示在接收 RichTextBox 控件中。启动接收线程时需要使用 Invoke 方法来更新界面状态,否则会出现“跨线程访问控件异常”的错误。
阅读全文