通过NetworkStream(套接字)写入/读取字符串以进行聊天

本文关键字:字符串 聊天 读取 NetworkStream 套接字 写入 通过 | 更新日期: 2023-09-27 18:24:43

如果这很难理解,很抱歉,第一次尝试C#。

我正在尝试在连接到服务器的客户端之间进行简单的公开"聊天"。我尝试过将整数传递到服务器并打印出来,一切都很好,但是,当我切换到字符串时,它似乎只能传递1个字符(因为ns.Write(converted, 0, 1);)。如果我增加ns。当我输入少于10个字符的消息时,向ns.Write(converted,0,10)写入所有内容(客户端和服务器)都会崩溃。

服务器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace MultiServeris
{
    class Multiserveris
    {
        static void Main(string[] args)
        {
            TcpListener ServerSocket = new TcpListener(1000);         
            ServerSocket.Start();                                     
            Console.WriteLine("Server started");
            while (true)
            {
                TcpClient clientSocket = ServerSocket.AcceptTcpClient();        
                handleClient client = new handleClient();                       
                client.startClient(clientSocket);
            }
        }
    }
    public class handleClient
    {
        TcpClient clientSocket;
        public void startClient(TcpClient inClientSocket)
        {
            this.clientSocket = inClientSocket;
            Thread ctThread = new Thread(Chat);
            ctThread.Start();
        }
        private void Chat()
        {
            byte[] buffer = new byte[10]; 
            while (true)
            {
                NetworkStream ns = clientSocket.GetStream();
                ns.Read(buffer,0,1);
                string line = Encoding.UTF8.GetString(buffer);
                Console.WriteLine(line);
            }
        }
    }
}

客户代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace Klientas
{
    class Klientas
    {
        static void Main(string[] args)
        {
            while (true)
            {
                TcpClient clientSocket = new TcpClient("localhost", 1000);
                NetworkStream ns = clientSocket.GetStream();
                byte[] buffer = new byte[10];
                string str = Console.ReadLine();
                byte[] converted = System.Text.Encoding.UTF8.GetBytes(str);
                ns.Write(converted, 0, 1);
            }
        }
    }
}

通过NetworkStream(套接字)写入/读取字符串以进行聊天

最好使用BinaryReader/BinaryWriter类来正确格式化和读取数据。这样就不需要自己处理了。例如在客户端做:

BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);

在服务器中:

BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());

当在同一个流上使用BinaryReader或BinaryWriter时,并且您有.NET framework 4.5或更高版本,请确保使用重载保持底层流打开:

using (var w = new BinaryWriter(stream, Encoding.UTF8, true)) {}