C#从套接字接收数据并将其放入字符串中?

Han*_*man 5 c# sockets

我有一个套接字服务器,正在尝试从客户端接收一个字符串。

客户端是完美的,当我使用它时

Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine(k);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++) {
    Console.Write(Convert.ToChar(b[i]));
    ASCIIEncoding asen = new ASCIIEncoding();
    s.Send(asen.GetBytes("The string was recieved by the server."));
}
Run Code Online (Sandbox Code Playgroud)

一切正常,我在控制台中得到了我的字符串。

但是我现在如何将我的接收放入一个字符串中,以便我可以在开关盒中使用它?

像这样:

string action = Convert.ToChar(b[i]);
Run Code Online (Sandbox Code Playgroud)

错误:

Name i 不在当前上下文中。这是我收到的唯一错误消息。

Rod*_*eis 5

这样就不需要设置缓冲区大小,它适合响应:

public static byte[] ReceiveAll(this Socket socket)
    {
        var buffer = new List<byte>();

        while (socket.Available > 0)
        {
            var currByte = new Byte[1];
            var byteCounter = socket.Receive(currByte, currByte.Length, SocketFlags.None);

            if (byteCounter.Equals(1))
            {
                buffer.Add(currByte[0]);
            }
        }

        return buffer.ToArray();
    }
Run Code Online (Sandbox Code Playgroud)


Max*_*rdt 4

假设您调用 receives是一个对象,您会得到一个返回值。要将其转换回字符串,请使用适当的编码,例如Socketbyte[]

string szReceived = Encoding.ASCII.GetString(b);
Run Code Online (Sandbox Code Playgroud)

编辑:由于缓冲区b始终为 100 字节,但实际接收到的字节数因每个连接而异,因此应该使用调用的返回值Socket.Receive()来仅转换实际接收到的字节数。

byte[] b = new byte[100];
int k = s.Receive(b);
string szReceived = Encoding.ASCII.GetString(b,0,k); 
Run Code Online (Sandbox Code Playgroud)