在C#中實現TCP/IP聊天應用,可以使用Socket類來實現客戶端和服務端的通信。以下是一個簡單的示例代碼:
服務端代碼:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Server
{
static void Main()
{
TcpListener server = new TcpListener(IPAddress.Any, 8888);
server.Start();
Console.WriteLine("Server started");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected");
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
while (true)
{
int bytes = stream.Read(data, 0, data.Length);
string message = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Client: " + message);
Console.Write("Server: ");
message = Console.ReadLine();
data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
}
client.Close();
server.Stop();
}
}
客戶端代碼:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Client
{
static void Main()
{
TcpClient client = new TcpClient("127.0.0.1", 8888);
Console.WriteLine("Connected to server");
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
while (true)
{
Console.Write("Client: ");
string message = Console.ReadLine();
data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
int bytes = stream.Read(data, 0, data.Length);
message = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Server: " + message);
}
client.Close();
}
}
在這個示例中,服務端監聽端口8888,并等待客戶端連接。客戶端連接到服務端后,可以發送和接收消息。服務端和客戶端都可以輸入消息并發送給另一方。
請注意,這只是一個簡單的示例,實際的聊天應用可能需要更多功能和處理邏輯,比如處理多個客戶端連接、消息格式處理、錯誤處理等。