帮我用C#winform写一个局域网聊天的代码
时间: 2024-10-29 09:19:55 浏览: 11
在C# Winform中创建一个简单的局域网聊天程序需要一些网络编程的基础知识,包括Socket通信和多线程处理。下面是一个基本的示例代码框架,展示了如何创建客户端和服务端的基本功能:
首先,我们需要创建一个服务器端的`ServerForm.cs`:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public partial class ServerForm : Form
{
private TcpListener listener;
public ServerForm()
{
InitializeComponent();
StartServer();
}
private void StartServer()
{
listener = new TcpListener(IPAddress.Any, 8080); // 使用8080端口
listener.Start();
labelStatus.Text = "等待连接...";
while (true)
{
Console.WriteLine("等待连接...");
var client = listener.AcceptTcpClient(); // 接受新的连接
Thread clientThread = new Thread(new ParameterizedThreadStart(ClientThreadProcedure));
clientThread.Start(client);
}
}
private void ClientThreadProcedure(object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
string message = "";
while ((message = reader.ReadLine()) != null)
{
textBoxMessages.AppendText(message + "\n");
SendToAllClients(writer, message);
}
client.Close();
}
private void SendToAllClients(StreamWriter writer, string message)
{
foreach (var conn in connections) // 假设connections存储了所有连接的客户端
{
if (conn != writer.BaseStream)
conn.Write(Encoding.ASCII.GetBytes(message));
}
}
}
```
然后,创建一个客户端的`ClientForm.cs`,这里我们假设有一个全局的`List<TcpClient>` `connections` 来保存所有的连接:
```csharp
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Text;
public partial class ClientForm : Form
{
public ClientForm(string ipAddress, int port)
{
InitializeComponent();
Connect(ipAddress, port);
}
private TcpClient client;
private void Connect(string ipAddress, int port)
{
try
{
client = new TcpClient(ipAddress, port);
connectionBox.AppendText($"已连接到服务器 {ipAddress}:{port}\n");
NetworkStream stream = client.GetStream();
SendTextBox.Text = "开始发送消息";
SendMessage(stream);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SendMessage(NetworkStream stream)
{
string input = sendTextBox.Text;
byte[] data = Encoding.ASCII.GetBytes(input);
stream.Write(data, 0, data.Length);
sendTextBox.Clear();
}
}
```
为了实现局域网范围内的通信,你需要确保服务器和客户端都在同一个局域网内。注意这只是一个非常基础的示例,实际应用中还需要考虑错误处理、用户身份验证、消息格式化等复杂情况。
阅读全文