简体   繁体   English

C#套接字刚收到第一条消息

[英]C# socket just first message received

I have searched many examples and tutorials and what not but I cant for the life of me figure out what im doing wrong here... If I send several messages to this server I made only the first is printed in the Console.Writeline command and the rest is never printed... I must be doing something fundametally wrong but I really cant find it ... :S 我搜索了许多示例和教程,但没有搜索过,但是我一生都无法弄清楚我在这里做错了什么...如果我向该服务器发送了几条消息,我只会在Console.Writeline命令中打印第一个消息,并且其余的从未打印过...我一定是在做一些根本性的错误,但是我真的找不到它...:S

This is the server code: 这是服务器代码:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms.VisualStyles;

namespace HL7_Manager
{
public class MonitorServer
{
    private int _port;
    private Socket _serverSocket;
    private List<ClientObject> _clients;

    public bool IsConnected { get; set; }
    public MonitorServer(int port)
    {
        _port = port;
        _clients = new List<ClientObject>();
    }

    public void StartListening()
    {
        _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        Thread listenThread = new Thread(new ThreadStart(ListenerThread));
        listenThread.IsBackground = true;
        listenThread.Start();
    }

    public void StopListening()
    {
        IsConnected = true;
        _serverSocket.Close();
        while (_clients.Count > 0)
        {
            _clients[0].KeepProcessing = false;
            _clients[0].ClientSocket.Close();
            _clients.RemoveAt(0);
        }
    }

    private void ListenerThread()
    {
        _serverSocket.Bind(new IPEndPoint(IPAddress.Any, _port));
        _serverSocket.Listen(100);

        Console.WriteLine("Listening on port 8000");

        while (true)
        {
            Socket clientSocket = _serverSocket.Accept();
            ClientObject client = new ClientObject();
            client.KeepProcessing = true;
            client.ClientSocket = clientSocket;
            _clients.Add(client);
            ParameterizedThreadStart ptStart = new ParameterizedThreadStart(ProcessClientThread);
            Thread processThread = new Thread(ptStart);
            processThread.IsBackground = true;
            processThread.Start(client);
            clientSocket = null;
            client = null;
        }
    }

    private void ProcessClientThread(object clientObj)
    {
        Console.WriteLine("Client connected");
        ClientObject client = (ClientObject) clientObj;
        Socket clientSocket = client.ClientSocket;
        byte[] buffer = new byte[clientSocket.ReceiveBufferSize];
        int receiveCount = 0;

        while (client.KeepProcessing)
        {
            try
            {
                receiveCount = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                Console.WriteLine(Encoding.ASCII.GetString(buffer));
            }
            catch (Exception ex)
            {
                if (!client.KeepProcessing)
                    return;
                Console.WriteLine(ex.Message);
            }
        }
        clientSocket.Close();
        _clients.Remove(client);
    }
}
}

Here is the method you should definitely change and how to change it. 这是您绝对应该更改的方法以及更改方法。

    private void ProcessClientThread(object clientObj)
    {
        Console.WriteLine("Client connected");
        ClientObject client = (ClientObject)clientObj;
        Socket clientSocket = client.ClientSocket;
        byte[] buffer = new byte[clientSocket.ReceiveBufferSize];
        int receiveCount = 0;

        while (client.KeepProcessing)
        {
            try
            {
                receiveCount = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                if (receiveCount == 0)
                    break; //the client has closed the stream
                var ret = Encoding.ASCII.GetString(buffer, 0, receiveCount);
                Console.WriteLine(ret);
            }
            catch (Exception ex)
            {
                if (!client.KeepProcessing)
                    return;
                Console.WriteLine(ex.Message);
            }
        }
        clientSocket.Close();
        _clients.Remove(client);
    }

Check how many bytes you really received. 检查您实际收到了多少个字节。 TCP is a streaming protocol this means that if you client is doing several sends of small messages right one after the other, you will receive them in one go at the receiver. TCP是一种流协议,这意味着如果您的客户端一次接一个地发送几次小消息,您将在接收器处一次性接收它们。 If there happens to be a null character in your receive buffer you might think you did not receive all those string, but actually you did. 如果您的接收缓冲区中碰巧有一个空字符,您可能会认为您没有收到所有这些字符串,但实际上您确实收到了。 Check this by inspecting how many bytes you received and by checking the buffer content. 通过检查您收到了多少字节并检查缓冲区内容来进行检查。 If you made this mistake there might be some deeper problem in your code. 如果您犯了此错误,则代码中可能存在更深层的问题。 The fact that TCP is streaming makes it a bit more complex TCP流式传输的事实使其变得更加复杂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM