温馨提示×

C# TcpIp如何实现聊天应用

c#
小樊
109
2024-07-22 21:51:07
栏目: 编程语言

在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,并等待客户端连接。客户端连接到服务端后,可以发送和接收消息。服务端和客户端都可以输入消息并发送给另一方。

请注意,这只是一个简单的示例,实际的聊天应用可能需要更多功能和处理逻辑,比如处理多个客户端连接、消息格式处理、错误处理等。

0