0

我已经在 c# 中使用 tcp/sockets 为客户端服务器编写了一个代码,它工作得非常好。我的问题是为什么我只能在单个实例中从客户端向服务器发送有限大小的数据。

以下是我的服务器代码

public class AsynchIOServer
{
// server port number
const int port = 8001;
// server ip address
const string ip = "127.0.0.1";

const int maxBuffer = 10000;

static IPAddress ipAddress = IPAddress.Parse(ip);
static TcpListener tcpListener = new TcpListener(ipAddress, port);


static void Listeners()
{
    try
    {
        Socket socketForClient = tcpListener.AcceptSocket();

        if (socketForClient.Connected)
        {
            Console.WriteLine("Client : " + socketForClient.RemoteEndPoint + " is now connected to server.");
            NetworkStream networkStream = new NetworkStream(socketForClient);
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
            System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);

            while (true)
            {
                string theString = streamReader.ReadLine();
                if (theString != "exit")
                {
                    // original message from client
                    Console.WriteLine("------------------------------------------------------------------------------");
                    Console.WriteLine("Message recieved from client(" + socketForClient.RemoteEndPoint + ") : " + theString);

                    // ASCII code for the message from client 
                    Console.Write("ASCII Code for message is : ");
                    foreach (char c in theString)
                    {
                        Console.Write(System.Convert.ToInt32(c) + " ");
                    }

                    // Hex value of message from client
                    string hex = "";
                    foreach (char c in theString)
                    {
                        int tmp = c;
                        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
                    }
                    Console.WriteLine();
                    Console.WriteLine("Hex Code for the message from client : " + hex);

                    //sending acknowledgement to client
                    Console.WriteLine();
                    socketForClient.Send(new ASCIIEncoding().GetBytes(/*"The string was recieved from Client(" + socketForClient.RemoteEndPoint + ") : " + */theString));

                } // end of if loop

                // if exit from client
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Client " + socketForClient.RemoteEndPoint + " has exited");
                    break;
                }

            } // end of  while loop

            streamReader.Close();
            networkStream.Close();
            streamWriter.Close();

        } // end of if loop

        socketForClient.Close();
        Console.WriteLine();
        // Console.WriteLine("Press any key to exit from server program");
        Console.ReadKey();

    } // end of try loop

    catch (Exception e) 
    {
        Console.WriteLine("The process failed: {0}", e.ToString());
        Console.WriteLine("Message not received from client");
    }

} // end of Listener loop

// Number of clients that can connect to the server
public static void Main()
{
    tcpListener.Start();

    Console.WriteLine("********** This is the Server program **********");
    Console.Write("Number of Clients that can connect to Server : ");

    int numberOfClientsYouNeedToConnect = int.Parse(Console.ReadLine());
    for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
    {
        Thread newThread = new Thread(new ThreadStart(Listeners));
        newThread.Start();
    }
    Console.WriteLine();

} // end of Min Loop

} // end of public class AsynchIOServer

而我的客户代码是

public class Client
{
// For acknowledgement from server
const int maxBuffer = 1000;

static public void Main(string[] Args)
{
    // ip address of server to which client should be connected
    string ip;
    // port number at which server is listening for client connection
    int port;

    Console.Write("Enter the ip address: ");
    ip = Console.In.ReadLine();

    Console.Write("Enter the port number: ");
    port = int.Parse(Console.In.ReadLine());

    TcpClient socketForServer;

    try
    {
        // connect to server at ipaddress ip and port number port
        socketForServer = new TcpClient(ip, port);
    }
    catch
    {
        Console.WriteLine("Failed to connect to server at {0}:{1}", ip , port);
        Console.ReadLine();
        return;
    }

    // Initializing StreamReader and StreamWriter for sending or reading message from server
    NetworkStream networkStream = socketForServer.GetStream();
    System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);
    System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);

    try
    {
        Console.WriteLine();
        Console.WriteLine("---Begin sending message(type 'exit' to disconnect from server)---");
        Console.WriteLine();

        Console.Write("Type message : ");
        string str = Console.ReadLine();

        while (str != "exit")
        {
            streamWriter.WriteLine(str);
            streamWriter.Flush();

            // For receiving acknowledgement from server
            byte[] receiveBuffer = new byte[maxBuffer];
            int k = networkStream.Read(receiveBuffer, 0, maxBuffer);
            for (int i = 0; i < k; i++)
                Console.Write(/*Convert.ToChar(*/receiveBuffer[i]);
            Console.WriteLine();
            Console.WriteLine("------------------------------------------------------");

            Console.Write("Type message : ");
            str = Console.ReadLine();
        }

        // For client to close connection with server
        if (str == "exit")
        {
            streamWriter.WriteLine(str);
            streamWriter.Flush();
        }
    } // end of try loop

    catch
    {
        Console.WriteLine("Exception reading from Server");
    }

    // exit the client
    networkStream.Close();
    Console.WriteLine("Press any key to exit from client program");
    Console.ReadKey();

} // End of Main loop

} // End of public class Client

现在,当我运行我的程序时,我输入以下二进制文件作为第一条消息从客户端发送

Type message : 11111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111111111111 11111111111111111111111111111

问题是它不允许我输入更多的二进制数据。如果我想通过按回车键发送更多二进制数据,然后作为第二条消息发送,我可以发送更多二进制数据。但我想将其作为单个消息发送。那么他们在单个实例上通过 tcp/sockets 发送更多数据有什么限制吗?

4

2 回答 2

1

你对问题的评估是错误的。没有消息——TCP 没有应用程序级别的消息,因为 TCP 不是消息协议,它是提供字节流的字节流协议,而不是消息。没有“作为单个消息发送”之类的东西,也没有“作为第二条消息发送”之类的东西。它只是发送字节和接收字节。如果您想接收更多字节,请再次调用接收。

如果你想实现消息,你可以这样做。但你必须这样做。您必须定义、指定和实现在 TCP 之上发送和接收消息的协议。您必须指定如何分隔消息、发送分隔消息并编写接收代码以检测分隔符并将接收到的字节流组装成消息。它不会自己发生。

最简单的解决方案是读取和写入由换行符分隔的,假设您的“消息”不能包含换行符。

于 2013-08-09T07:33:03.413 回答
0

这与 ReadLine 方法将输入限制为 256 个字符有关,有关解决方法,请参阅备注部分:

http://msdn.microsoft.com/en-us/library/system.console.readline.aspx

编辑:错字

于 2013-08-09T07:33:48.033 回答