Ç的Winsock编程:输入垃圾 [英] C Winsock programming: input garbage

查看:142
本文介绍了Ç的Winsock编程:输入垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的这个code样品编程一个非常简单的socket服务器。服务器启动并运行,我可以(用腻子,实际上)通过telnet连接到它。每当接收到一个新的连接,我产生一个新的线程如下code:

I'm programming a very simple socket server following this sample code. The server is up and running and I can connect to it via telnet (using Putty, actually). Whenever a new connection is received, I spawn a new thread that is the following code:

DWORD WINAPI receive_cmds(LPVOID lpParam) 
{
      char outbuffer[100];
      outbuffer[0] = '\0';
      char inbuffer[100];
      inbuffer[0] = '\0';
      int res;
      SOCKET current_client = (SOCKET)lpParam;

      while (1) {           
          res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
          if (res > 0) {
              inbuffer[res] = '\0';
              printf("Got '%s'\n", inbuffer);
          }              
          Sleep(10);

          if (res == 0) {
             closesocket(current_client);
             ExitThread(0);             
          }                          

          //printf("%s\n", inbuffer); 
          strcpy(inbuffer, "");
      }
}

当我将它连接打印此乱码:

As soon as I connect it prints this gibberish:

如果我输入你好,并在客户端然后计算器,这是我所得到的:

If i input "hello" and then "stackoverflow" in the client, this is what I get:

即使我宣布线'\\ 0'的明确的结束,似乎把更多的路线,再加上我不知道为什么它打印输入两次,第二个是第一个减去第一一个或两个字符。

Even if I declared explicitly the end of line '\0', it seems to take much more of the line, plus I don't know why it prints the input two times, the second being the first one minus the first one or two characters.

在理解到底是怎么回事任何帮助吗?先谢谢了。

Any help on understanding what is going on? Thanks in advance.

编辑:编辑相应什么建议由开卷

edited accordingly to what suggested by unwind

推荐答案

您应该做得更好错误检查和更明智的缓冲处理:

You should do better error-checking, and more sensible buffer handling:

res = recv(current_client, inbuffer, sizeof(inbuffer), 0);

res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
if (res > 0)
{
  inbuffer[res] = '\0';
  printf("Got '%s'\n", inbuffer);
}

您需要在缓冲区的终止符留出空间,所以你不能使用缓冲区的所有接收数据。而且你应该检查-1,并终止缓冲区,使之成为一个字符串打印它是这样了。

You need to leave space in the buffer for the terminator, so you can't use all of the buffer to receive data. And you should check for -1, and terminate the buffer to make it into a string before printing it as such.

这篇关于Ç的Winsock编程:输入垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆