简体   繁体   English

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

[英]C# Receive Data from Socket and put it in a String?

I have a socket server and am trying to receive a string from the client. 我有一个套接字服务器,我试图从客户端收到一个字符串。

The client is perfect and when I use this 当我使用它时,客户端是完美的

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."));
}

All is okay and I get my string in the console. 一切都还好,我在控制台中得到了我的字符串。

But how can I get now my receive into a string so I can use it in a switch case? 但是我如何才能将我的接收变成一个字符串,以便在开关盒中使用它?

Like this: 像这样:

string action = Convert.ToChar(b[i]);

Error: 错误:

The Name i isn't in the current context. 名称i不在当前上下文中。 its the only Error Message i get. 它是我得到的唯一错误消息。

Init socket Init套接字

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(m_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, m_port);

Connect socket 连接插座

socket.Connect(remoteEP);

Receive from socket 从套接字接收

byte[] buffer = new byte[1024];
int iRx = socket.Receive(buffer);
char[] chars = new char[iRx];

System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);

Send message 发信息

byte[] byData = System.Text.Encoding.ASCII.GetBytes("Message");
socket.Send(byData);

Close socket 关闭插座

socket.Disconnect(false);
socket.Close();

Assuming s is a Socket object on which you call receive, you get an byte[] back. 假设s是一个你调用receive的Socket对象,你会得到一个byte[] To convert this back to a string, use the appropiate encoding, eg 要将其转换回字符串,请使用适当的编码,例如

string szReceived = Encoding.ASCII.GetString(b);

Edit: Since the buffer b is always 100 bytes, but the actual number of bytes received varies with each connection, one should use the return value of the Socket.Receive() call to only convert the actual number of received bytes. 编辑:由于缓冲区b总是100个字节,但实际接收的字节数随每个连接而变化,因此应该使用Socket.Receive()调用的返回值来仅转换实际接收的字节数。

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

This way no need set buffer size, it fits to response: 这种方式不需要设置缓冲区大小,它适合响应:

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();
    }

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

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