C#Socket接收到字符串

时间:2016-01-27 11:56:15

标签: c# sockets

关注this guide我写了以下函数:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    secondVC *secVC=[[secondVC alloc] init];
    [secVC prepareArrays];

    fetchFromParse *fetchFromParseObj=[[fetchFromParse alloc] init];
    [fetchFromParseObj getStoresFromParse];

    Return YES;
}

但我收到错误

  

使用未分配的局部变量'bytes'和使用未分配的局部变量'byteRecieve'

代码谎言

public string ConnectToHost(string ip, int port)
{
    Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

    IPAddress host = IPAddress.Parse(ip);
    IPEndPoint ipep = new IPEndPoint(host, port);

    socket.Connect(ipep);

    byte[] msg = Encoding.Unicode.GetBytes("<Client Quit>");
    int msgSend = socket.Send(msg);

    byte[] bytes;
    int byteRecieve;

    String msgRecieved = Encoding.Unicode.GetString(bytes, 0, byteRecieve);
    while (socket.Available > 0)
    {
        byteRecieve = socket.Receive(bytes);
        msgRecieved += Encoding.Unicode.GetString(bytes, 0, byteRecieve);
    }

    socket.Shutdown(SocketShutdown.Both);
    socket.Close();

    return msgRecieved;
}

从该行中移除String msgRecieved = Encoding.Unicode.GetString(bytes, 0, byteRecieve); 并且只有Encoding.Unicode.GetString(bytes, 0, byteRecieve);String msgRecieved;循环内发出相同的错误。

如何让此函数将收到的字节作为字符串返回?

2 个答案:

答案 0 :(得分:2)

嗯,你确实在没有分配这些变量的情况下使用这些变量,不是吗?这是不允许的,因为不清楚这意味着什么。在这种情况下,您可以通过说:

使其工作
    byte[] bytes = new byte[4096];
    int byteRecieve = 0;

当您解决了与套接字无关的编译器错误时,您会发现使用Available低估了传入的数据量。它几乎没用。

此外,您会发现Unicode编码的字符串无法在任意边界处分解,因此这也不起作用。使用StreamReader

你可能应该继续寻找不同的教程。大多数都非常破碎。 TCP很难做对。

答案 1 :(得分:0)

看看这两行代码:

public async Task<bool> UpvoteArticleAsync(string source, string url)
{
    var request = HttpWebRequest.Create(string.Format(@"http://192.168.43.199:8080/service/upvote/{0}/{1}", source, url));
    request.ContentType = "application/json";
    request.Method = "GET";

    using (HttpWebResponse response = await request.GetResponseAsync () as HttpWebResponse)
    {
        if (response.StatusCode != HttpStatusCode.OK)
            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            var content = reader.ReadToEnd();
            if(string.IsNullOrWhiteSpace(content)) {
                Console.Out.WriteLine("Response contained empty body...");
            }
            else {
                Console.Out.WriteLine("Response Body: \r\n {0}", content);
            }
        }
    }
    return true;
}

int byteRecieve;

在第一行中,您声明String msgRecieved = Encoding.Unicode.GetString(bytes, 0, byteRecieve); ,但不为其指定值。在第二行中,您可以使用它。由于您尚未为其分配值,因此会收到错误消息。

由于你在byteRecieve循环中做了正确的事情,你可以简单地删除上面的第二行......

另外

while

应该变得像

byte [] bytes;

或类似的。同样,您的版本仅将byte [] bytes = new bytes[256]; 声明为字节数组,但未向其分配/分配实际数组值。