生成winform版的socket服务端源码
时间: 2023-08-31 14:38:27 浏览: 177
### 回答1:
以下是一个简单的 Windows Forms 版本的 Socket 服务端代码示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace SocketServer
{
public partial class Form1 : Form
{
private Socket serverSocket;
private byte[] buffer = new byte[1024];
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
// 创建服务器 Socket 对象
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(txtPort.Text));
serverSocket.Bind(endPoint);
serverSocket.Listen(10);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult AR)
{
Socket socket = serverSocket.EndAccept(AR);
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
textBox1.Invoke((MethodInvoker)delegate
{
textBox1.AppendText(text + "\r\n");
});
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
serverSocket.Close();
}
}
}
```
这是一个基于异步通信的简单 Socket 服务端示例,它使用 Windows Forms 来显示连接到服务器的客户端发送的信息。它使用 `BeginAccept` 和 `BeginReceive` 方法实现异步通信。该代码仅供参考,可以根据需要进行修改和扩展。
### 回答2:
以下是一个简单的WinForm版的Socket服务端源码示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
public class SocketServerForm : Form
{
private TextBox textBox;
private Button startButton;
private Button stopButton;
private bool isListening;
private Socket listenerSocket;
private Thread listenThread;
public SocketServerForm()
{
this.Text = "Socket Server";
this.Size = new System.Drawing.Size(400, 300);
this.textBox = new TextBox();
this.textBox.Multiline = true;
this.textBox.Dock = DockStyle.Fill;
this.Controls.Add(textBox);
this.startButton = new Button();
this.startButton.Text = "Start";
this.startButton.Dock = DockStyle.Bottom;
this.startButton.Click += StartButton_Click;
this.Controls.Add(startButton);
this.stopButton = new Button();
this.stopButton.Text = "Stop";
this.stopButton.Dock = DockStyle.Bottom;
this.stopButton.Enabled = false;
this.stopButton.Click += StopButton_Click;
this.Controls.Add(stopButton);
}
private void StartButton_Click(object sender, EventArgs e)
{
isListening = true;
listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenerSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
listenerSocket.Listen(10);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
startButton.Enabled = false;
stopButton.Enabled = true;
textBox.AppendText("Server started.\r\n");
}
private void StopButton_Click(object sender, EventArgs e)
{
isListening = false;
listenerSocket.Close();
listenThread.Join();
startButton.Enabled = true;
stopButton.Enabled = false;
textBox.AppendText("Server stopped.\r\n");
}
private void ListenForClients()
{
while (isListening)
{
Socket clientSocket;
try
{
clientSocket = listenerSocket.Accept();
}
catch (SocketException)
{
if (isListening)
continue;
else
return;
}
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCommunication));
clientThread.Start(clientSocket);
}
}
private void HandleClientCommunication(object clientSocket)
{
Socket socket = (Socket)clientSocket;
byte[] buffer = new byte[1024];
StringBuilder messageBuilder = new StringBuilder();
while (true)
{
int bytesRead = socket.Receive(buffer);
messageBuilder.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
if (messageBuilder.ToString().EndsWith("<EOF>"))
{
break;
}
}
string receivedMessage = messageBuilder.ToString().Replace("<EOF>", "");
textBox.Invoke((MethodInvoker)delegate {
textBox.AppendText("Received: " + receivedMessage + "\n");
});
socket.Send(Encoding.ASCII.GetBytes("Message received."));
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
public static void Main()
{
Application.Run(new SocketServerForm());
}
}
```
该示例使用了Windows Form进行界面设计,提供了"Start"和"Stop"按钮来控制服务端的运行和停止。通过点击"Start"按钮,服务端会创建一个监听Socket,并开始接受客户端的连接请求。当有客户端连接时,会为每个客户端创建一个独立的线程来处理与该客户端的通信,当收到完整的消息后,会在文本框中显示接收到的消息,并回复客户端"Message received."的确认消息。
注意:该示例为一个简单的Socket服务端代码,可能还需要根据实际需求进行修改和完善。
阅读全文