聊天应用程序写空行

本文关键字:应用程序 聊天 | 更新日期: 2023-09-27 18:05:57

我制作了一个具有以下模型的聊天应用程序(客户端+服务器(:http://csharp.net-informations.com/communications/csharp-chat-server-programming.htm

不同的是,我也在控制台应用程序中创建了客户端。这是我的客户端类的代码:

class Program
{
    static TcpClient clientSocket = new TcpClient();
    static NetworkStream serverStream = default(NetworkStream);
    static string readData = null;
    static void Main(string[] args)
    {
        connect();
        while (true)
        {
        string send = Console.ReadLine();
        byte[] outStream = Encoding.ASCII.GetBytes(send + "$");
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();
        }
    }
    private static void connect()
    {
            readData = "Connected to Chat Server...";
            msg();
            clientSocket.Connect("localhost", 8888);
            serverStream = clientSocket.GetStream();
            byte[] outStream = Encoding.ASCII.GetBytes("somerandomusername" + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
    }
    private static void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            string returndata = Encoding.ASCII.GetString(inStream);
            if (returndata != null)
            {
                readData = "" + returndata;
                msg();
            }
        }
    }
    private static void msg()
    {
        Console.WriteLine(">> " + readData);
    }
}

这是我的服务器类的代码:

class Program
{
    public static Hashtable clientsList = new Hashtable();
    static void Main(string[] args)
    {
        TcpListener serverSocket = new TcpListener(8888);
        TcpClient clientSocket = default(TcpClient);
        int counter = 0;
        serverSocket.Start();
        Console.WriteLine("Server started...");
        counter = 0;
        while ((true))
        {
            counter += 1;
            clientSocket = serverSocket.AcceptTcpClient();
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
            NetworkStream networkStream = clientSocket.GetStream();
            networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
            dataFromClient = Encoding.ASCII.GetString(bytesFrom);
            dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
            clientsList.Add(dataFromClient, clientSocket);
            broadcast(dataFromClient + " Joined", dataFromClient, false);
            Console.WriteLine(dataFromClient + " Joined chat room");
            handleClient client = new handleClient();
            client.startClient(clientSocket, dataFromClient, clientsList);
        }
        clientSocket.Close();
        serverSocket.Stop();
        Console.WriteLine("exit");
        Console.ReadLine();
    }
    public static void broadcast(string msg, string uName, bool flag)
    {
        foreach (DictionaryEntry client in clientsList)
        {
            TcpClient broadcastSocket;
            broadcastSocket = (TcpClient)client.Value;
            NetworkStream broadcastStream = broadcastSocket.GetStream();
            Byte[] broadcastBytes = null;
            if (flag == true)
            {
                broadcastBytes = Encoding.ASCII.GetBytes(uName + ": " + msg);
            }
            else
            {
                broadcastBytes = Encoding.ASCII.GetBytes(msg);
            }
            broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
            broadcastStream.Flush();
        }
    }
}
public class handleClient
{
    TcpClient clientSocket;
    string clNo;
    Hashtable clientsList;
    public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
    {
        this.clientSocket = inClientSocket;
        this.clNo = clineNo;
        this.clientsList = cList;
        Thread ctThread = new Thread(doChat);
        ctThread.Start();
    }
    private void doChat()
    {
        int requestCount = 0;
        byte[] bytesFrom = new byte[10025];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        string serverResponse = null;
        string rCount = null;
        requestCount = 0;
        while ((true))
        {
            try
            {
                requestCount = requestCount + 1;
                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
                rCount = Convert.ToString(requestCount);
                Program.broadcast(dataFromClient, clNo, true);
            }
            catch (Exception ex)
            {
                clientsList.Remove(clNo);
                Console.WriteLine(clNo + " hat den Chat verlassen");
                break;
            }
        }
    }
}

不知怎的,客户端在接收消息时显示了很多空行。这是一张截图:https://i.stack.imgur.com/CoF5B.png.在第一个红色标记的上方有空行。它标记了我输入消息、按回车键和编写服务器响应的区域。要看到它,我必须向下滚动到红色标记。然后是空行。第二个红色标记标记下一个消息将出现的区域。

如果你能帮我解决这个问题,我将不胜感激。

聊天应用程序写空行

我知道你的问题是(客户端中(修复的代码:

private static void getMessage()
{
    while (true)
    {
        serverStream = clientSocket.GetStream();
        int buffSize = 0;
        buffSize = clientSocket.Available;
        byte[] inStream = new byte[buffSize];
        serverStream.Read(inStream, 0, buffSize);
        string returndata = Encoding.ASCII.GetString(inStream);
        if (returndata != null)
        {
            readData = "" + returndata;
            msg();
        }
    }
}

您在哪里将缓冲区大小读取到您想要的可用字节的数组中。

David

您确定收到任何文本吗?您发送的文本是否正确?你有什么错误吗?在数据广播之前设置断点,在接收端设置断点,并检查变量是否包含您期望的内容。

难道你不是在试图从没有任何数据的流中读取,并给你提供了dummydata,导致应用程序打印没有文本的新行,因为它没有文本可发送吗?

空文本的行数与您发送的字符串的长度相同吗?

您的问题是Encoding.ASCII.GetString的误用:字节值0将被转换为空间,而不是像您可能怀疑的那样转换为''0'。由于你用10025个零初始化它,所以你的行中有很多空格。在将returndata附加到readData之前修剪它可以解决这个问题,但也会产生副作用,比如不允许在消息中使用前导和尾随空格。

你可以试试这个来理解问题:

static void Main(string[] args)
{
    byte[] lolempty = new byte[1024];
    string encoded = Encoding.ASCII.GetString(lolempty);
    Console.WriteLine(encoded.Length.ToString());
    Console.WriteLine("[{0}]", encoded);
}