这里是 C# 制作简单的多人在线即时交流聊天室的攻略。下面我们将分步骤介绍实现过程。
准备工作
- 编程环境:Visual Studio 2017 或更高版本。
- 知识储备:C# .NET 基础知识、Socket 编程、多线程编程、WinForm 界面开发等。
实现步骤
1. 创建 WinForm 应用程序
打开 Visual Studio,创建一个新的 WinForm 应用程序项目。该项目的名字为 ChatRoom。
2. 设计聊天界面
在设计窗口中添加四个控件,以实现多人即时聊天室:
- 一个 ListBox 控件,用于显示聊天记录。
- 一个 TextBox 控件,用于输入发送的内容。
- 一个 Button 控件,用于发送消息。
- 一个 Label 控件,用于显示在线用户的数量。
3. 实现服务器端
服务器端将使用 C# Socket 编程实现。在解决方案资源管理器中创建一个名为 Server 的新控制台应用程序项目,并添加以下代码:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Server {
class Program {
static Hashtable clientsList = new Hashtable();
static void Main(string[] args) {
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8080);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Server started...");
while (true) {
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.Unicode.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
Broadcast(dataFromClient + " joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " joined chat room ");
handleClient client = new handleClient();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string uName, bool flag) {
foreach (DictionaryEntry Item in clientsList) {
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag) {
broadcastBytes = Encoding.Unicode.GetBytes(uName + " says : " + msg);
} else {
broadcastBytes = Encoding.Unicode.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
}
}
public class handleClient {
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList) {
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat() {
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
string dataFromClient = null;
while (true) {
try {
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.Unicode.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Program.Broadcast(dataFromClient, clNo, true);
} catch {
Console.WriteLine(clNo + " disconnected");
clientsList.Remove(clNo);
Broadcast(clNo + " disconnected", "", false);
break;
}
}
}
public void Broadcast(string msg, string uName, bool flag) {
byte[] broadcastBytes = null;
if (flag) {
broadcastBytes = Encoding.Unicode.GetBytes(uName + " says : " + msg);
} else {
broadcastBytes = Encoding.Unicode.GetBytes(msg);
}
NetworkStream broadcastStream = clientSocket.GetStream();
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
}
}
4. 实现客户端
客户端也使用 C# Socket 编程实现。在 ChatRoom 项目中添加一个新的类,名为 ChatClient,并添加以下代码:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace ChatRoom {
public partial class ChatClient : Form {
private TcpClient clientSocket = new TcpClient();
private NetworkStream serverStream = default(NetworkStream);
private string readData = null;
public ChatClient() {
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e) {
readData = "Connecting to chat room server...";
msg();
clientSocket.Connect("127.0.0.1", 8080);
serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.Unicode.GetBytes(txtUser.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private void btnSend_Click(object sender, EventArgs e) {
byte[] outStream = Encoding.Unicode.GetBytes(txtMsg.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
txtMsg.Text = "";
}
private void getMessage() {
while (true) {
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[clientSocket.ReceiveBufferSize];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.Unicode.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg() {
if (InvokeRequired) {
this.Invoke(new MethodInvoker(msg));
} else {
lstChat.Items.Add(readData);
}
}
}
}
5. 编译并运行聊天室
编译两个项目,启动 ChatRoom 服务器应用程序,并运行 ChatClient 客户端应用程序。在客户端中输入用户名,然后单击“连接”按钮即可加入聊天室。在聊天室中输入消息,然后按下“发送”按钮即可将消息发送给所有在线用户。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#制作简单的多人在线即时交流聊天室 - Python技术站