用VS搭建一个聊天室源码
时间: 2023-10-21 21:03:34 浏览: 67
下面是使用 Visual Studio 和 C# 搭建一个简单聊天室的源码示例:
Server 端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static List<Socket> clients = new List<Socket>();
static void Main(string[] args)
{
// 设置服务器 IP 地址和端口号
string ip = "127.0.0.1";
int port = 8000;
// 创建服务器 socket 对象
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定 IP 地址和端口号
serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
// 设置最大连接数
serverSocket.Listen(10);
Console.WriteLine("Server started, waiting for clients ...");
while (true)
{
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("Client {0} connected", clientSocket.RemoteEndPoint.ToString());
clients.Add(clientSocket);
// 创建新线程处理客户端请求
Task.Factory.StartNew(() =>
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
// 接收客户端消息
int receiveLength = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, receiveLength);
Console.WriteLine("Client {0} sent message: {1}", clientSocket.RemoteEndPoint.ToString(), message);
// 广播消息给所有客户端
foreach (Socket client in clients)
{
if (client == clientSocket) continue;
client.Send(Encoding.UTF8.GetBytes(message));
}
}
catch (Exception ex)
{
Console.WriteLine("Client {0} disconnected: {1}", clientSocket.RemoteEndPoint.ToString(), ex.Message);
clients.Remove(clientSocket);
clientSocket.Close();
break;
}
}
});
}
}
}
}
```
Client 端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
// 设置服务器 IP 地址和端口号
string ip = "127.0.0.1";
int port = 8000;
// 创建客户端 socket 对象
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接服务器
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
Console.WriteLine("Connected to server");
// 创建新线程接收服务器消息
Task.Factory.StartNew(() =>
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
// 接收服务器消息
int receiveLength = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, receiveLength);
Console.WriteLine("Received message from server: {0}", message);
}
catch (Exception ex)
{
Console.WriteLine("Server disconnected: {0}", ex.Message);
clientSocket.Close();
break;
}
}
});
// 发送消息
while (true)
{
string input = Console.ReadLine();
clientSocket.Send(Encoding.UTF8.GetBytes(input));
}
}
}
}
```
这个程序使用 C# 的 Socket 类创建了一个服务器和一个客户端,可以在本地运行。当客户端发送消息时,服务器会将该消息广播给所有连接到服务器的客户端。程序使用多线程处理客户端请求,可以同时处理多个客户端连接。
阅读全文