写一个C# 带样式Socket点对点通信,要求界面上有连接按钮,断开按钮,发送按钮,两个RichTextBox控件
时间: 2023-06-17 08:02:17 浏览: 187
以下是一个简单的C#带样式Socket点对点通信的例子,该例子包含连接按钮、断开按钮、发送按钮和两个RichTextBox控件(分别用于显示接收和发送的消息):
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SocketCommunication
{
public partial class Form1 : Form
{
private Socket clientSocket;
private Thread receiveThread;
private bool isRunning = true;
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (clientSocket != null && clientSocket.Connected)
{
MessageBox.Show("Already connected.");
return;
}
try
{
IPAddress ip = IPAddress.Parse(txtIP.Text);
int port = int.Parse(txtPort.Text);
IPEndPoint endPoint = new IPEndPoint(ip, port);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(endPoint);
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
MessageBox.Show("Connected successfully.");
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect: " + ex.Message);
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (clientSocket == null || !clientSocket.Connected)
{
MessageBox.Show("Not connected yet.");
return;
}
isRunning = false;
receiveThread.Join();
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
clientSocket = null;
MessageBox.Show("Disconnected successfully.");
}
private void btnSend_Click(object sender, EventArgs e)
{
if (clientSocket == null || !clientSocket.Connected)
{
MessageBox.Show("Not connected yet.");
return;
}
string message = txtMessage.Text;
byte[] data = Encoding.UTF8.GetBytes(message);
try
{
clientSocket.Send(data);
AppendText(txtSent, message, true);
}
catch (Exception ex)
{
MessageBox.Show("Failed to send message: " + ex.Message);
}
}
private void ReceiveData()
{
while (isRunning)
{
try
{
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
if (count > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, count);
AppendText(txtReceived, message, false);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to receive data: " + ex.Message);
isRunning = false;
}
}
}
private void AppendText(RichTextBox richTextBox, string text, bool isSent)
{
if (richTextBox.InvokeRequired)
{
richTextBox.Invoke(new Action<RichTextBox, string, bool>(AppendText), richTextBox, text, isSent);
}
else
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = isSent ? System.Drawing.Color.Blue : System.Drawing.Color.Red;
richTextBox.AppendText(text + Environment.NewLine);
richTextBox.SelectionColor = richTextBox.ForeColor;
}
}
}
}
```
在界面设计器中,将以下控件添加到窗体上并设置其属性:
- 两个RichTextBox控件,分别命名为txtReceived和txtSent,用于显示接收和发送的消息。
- 三个Button控件,分别命名为btnConnect、btnDisconnect和btnSend,用于连接、断开和发送消息。
- 两个TextBox控件,分别命名为txtIP和txtPort,用于指定连接的IP地址和端口号。
然后,将btnConnect、btnDisconnect和btnSend的Click事件分别绑定到btnConnect_Click、btnDisconnect_Click和btnSend_Click方法,如下所示:
```csharp
private void btnConnect_Click(object sender, EventArgs e)
{
// ...
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
// ...
}
private void btnSend_Click(object sender, EventArgs e)
{
// ...
}
```
最后,实现ReceiveData和AppendText方法,用于接收数据并在RichTextBox控件中显示数据,如下所示:
```csharp
private void ReceiveData()
{
while (isRunning)
{
try
{
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
if (count > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, count);
AppendText(txtReceived, message, false);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to receive data: " + ex.Message);
isRunning = false;
}
}
}
private void AppendText(RichTextBox richTextBox, string text, bool isSent)
{
if (richTextBox.InvokeRequired)
{
richTextBox.Invoke(new Action<RichTextBox, string, bool>(AppendText), richTextBox, text, isSent);
}
else
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = isSent ? System.Drawing.Color.Blue : System.Drawing.Color.Red;
richTextBox.AppendText(text + Environment.NewLine);
richTextBox.SelectionColor = richTextBox.ForeColor;
}
}
```
这样,一个简单的C#带样式Socket点对点通信就完成了。
阅读全文