使用Winsock的基本通信 [英] Basic Communication using Winsock

查看:72
本文介绍了使用Winsock的基本通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用winsock玩一些游戏,但是我遇到了这个问题,我的recv()函数似乎没有收到.

Hi, I''m trying to play around a little with winsock, and I have this problem, where my recv() function doesn''t seem to receive.

char buf[1000];
	do
	{
		gets(buf);
		if ((int)buf[0] == 0)
			send(mysock, "\r\n", 2, 0);
		else
			send(mysock, buf, strlen(buf), 0);
		
		recv(mysock, buf, sizeof(buf), 0);
		printf(buf);

	} while (strcmp(buf,"~") != 0);



例如,我与此连接到谷歌.在我发送请求后,recv()函数使我的程序卡住了,并且没有获得从服务器发回给我的数据包.有什么问题?



I connect with this to google for example. After I send my request the recv() function gets my program stuck, and doesn''t get the packet that was sent back to me from the server. What is the problem?

推荐答案

连接到HTTP服务器时(我认为您在说Google时已连接到一台服务器)时,必须发送有效请求才能获得答案.这包括尾随CR-LF对(请参阅 RFC 2616 [
When connecting to a HTTP server (and I think you connected to one when saying Google) you must send valid requests to get an answer. This includes a trailing CR-LF pair (see RFC 2616[^]). The gets() function will remove the entered new line character. So the server receives your data but waits for the terminating CR-LF pair to process the request and answer.

But even when you add sending a CR-LF pair after your entered command, your code will probably fail. You are passing the length of the entered string as buffer size to your recv() call. You should read one of the many tutorials about Winsock to implement a receive function that handles received data of variable length.

You should also always check the return values of the send() and recv() calls.


这篇关于使用Winsock的基本通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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