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

use*_*132 3 c# sockets string chat networkstream

对不起,如果这很难理解,第一次尝试C#.

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

服务器代码:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

客户代码:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

tyr*_*nid 9

您最好使用BinaryReader/BinaryWriter类来正确格式化和读取数据.这消除了自己处理它的需要.例如在客户端做:

BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
Run Code Online (Sandbox Code Playgroud)

并在服务器中:

BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
Run Code Online (Sandbox Code Playgroud)


小智 5

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

using (var w = new BinaryWriter(stream, Encoding.UTF8, true)) {}
Run Code Online (Sandbox Code Playgroud)