winform 使用socket编写tcpip服务端
时间: 2023-07-23 20:32:54 浏览: 93
C#socket通讯 winform(服务端和客户端)
要使用WinForm编写TCP/IP协议的服务端程序,同样需要使用Socket类。下面是一个简单的示例代码,演示如何使用Socket类接收客户端连接,并发送和接收数据。
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TcpIpDemo
{
public partial class Form1 : Form
{
private Socket serverSocket;
private Thread listenThread;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
private void btnStart_Click(object sender, EventArgs e)
{
try
{
// 绑定端口并开始监听
serverSocket.Bind(new IPEndPoint(IPAddress.Any, int.Parse(txtPort.Text)));
serverSocket.Listen(10);
txtLog.AppendText("服务器已启动,等待客户端连接...\n");
// 启动监听线程
listenThread = new Thread(ListenThreadFunc);
listenThread.IsBackground = true;
listenThread.Start();
}
catch (Exception ex)
{
txtLog.AppendText("启动服务器失败:" + ex.Message + "\n");
return;
}
}
private void ListenThreadFunc()
{
while (true)
{
try
{
// 接受客户端连接
Socket clientSocket = serverSocket.Accept();
txtLog.AppendText("客户端已连接:" + clientSocket.RemoteEndPoint.ToString() + "\n");
// 启动接收数据的线程
ReceiveThreadStart(clientSocket);
}
catch (Exception ex)
{
txtLog.AppendText("接受客户端连接出错:" + ex.Message + "\n");
break;
}
}
}
private void ReceiveThreadStart(Socket clientSocket)
{
// 启动接收数据的线程
System.Threading.Thread receiveThread = new System.Threading.Thread(() => ReceiveThreadFunc(clientSocket));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveThreadFunc(Socket clientSocket)
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
// 接收数据
int count = clientSocket.Receive(buffer);
if (count > 0)
{
string msg = Encoding.UTF8.GetString(buffer, 0, count);
this.Invoke((Action)(() =>
{
txtLog.AppendText("收到客户端消息:" + msg + "\n");
// 发送回复
byte[] data = Encoding.UTF8.GetBytes("收到消息:" + msg);
clientSocket.Send(data);
}));
}
else
{
break;
}
}
catch (Exception ex)
{
txtLog.AppendText("接收数据出错:" + ex.Message + "\n");
break;
}
}
// 关闭连接
try
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
txtLog.AppendText("客户端已断开连接:" + clientSocket.RemoteEndPoint.ToString() + "\n");
}
catch (Exception ex)
{
txtLog.AppendText("关闭连接出错:" + ex.Message + "\n");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// 关闭监听
serverSocket.Close();
listenThread.Join();
}
catch (Exception ex)
{
txtLog.AppendText("关闭服务器出错:" + ex.Message + "\n");
}
}
}
}
```
在上面的示例代码中,我们使用了一个Socket对象来代表服务器端,使用Bind方法来绑定端口并开始监听。接收客户端连接时,我们使用了Accept方法,启动接收数据的线程时,我们使用了一个新的线程来执行ReceiveThreadFunc方法。在接收数据时,我们使用了Receive方法,发送数据时,我们使用了Send方法。为了能够在接收数据时更新UI,我们使用了Invoke方法来执行UI线程上的操作。
当窗口关闭时,我们使用Close方法来关闭服务器端,并等待监听线程结束。
阅读全文