【发布时间】:2017-01-16 13:39:41
【问题描述】:
所以我想在我的电脑上运行一个实时服务器来连接并从其他人那里获取信息。我以为我可以让其他人在未使用的端口上连接到我的 IP 地址。因此,例如,如果我假设的 IP 地址是 214.231.34.12 和端口 50000,我打开连接并将此信息提供给某人,他们可以连接到它并通过 TCP 向我发送信息。
我认为我可以使用此代码:
// TCPClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
/*
Live Server on port 50000
*/
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("214.231.34.12");
server.sin_family = AF_INET;
server.sin_port = htons(50000);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
puts("Connection accepted");
//Reply to the client
message = "Hello Client , I have received your connection. But I have to go now, bye\n";
send(new_socket, message, strlen(message), 0);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
但绑定连接失败。整个 TCP 和 winsocket 的东西对我来说是全新的,我不明白我应该如何以不同的方式处理这个问题。我知道这段代码还没有收到任何信息,这只是我目前尝试开始工作的连接。这不是设置它的正确方法吗?
bind() 失败并出现 Windows 套接字错误 10049
【问题讨论】:
-
这是您的代码还是您从某个地方获取的?
-
214.231.34.12 是您的 PC 或路由器的 IP,哪个做 NAT?如果您在带有 NAT 的路由器后面,则需要配置端口转发。另外,不要将您的套接字绑定到 IP,只需使用
INADDR_ANY,如果涉及 NAT 或您的 IP 更改,这会更容易。另外,请先在本地测试您的程序。 -
继续阅读有关套接字的书。你会达到http编程然后也许你可以这样做。不要在 http 和 tcp-udp/ip 之间混用。
-
在
bind上失败。您从bind打印出错误代码。编辑您的帖子以添加返回的错误代码可能会对我们有所帮助。 -
如果你想学习套接字等。我鼓励你从头开始编写代码,或者至少阅读并理解你在那里看到的每个函数。您还应该学习一般的网络通信(IP 和 TCP 的工作原理)。在网络通信中,很多事情都可能出错。最好有助于了解您在做什么,这样您至少可以缩小自己的问题范围。对于我们来说,要求您分析所有事情然后为您提出解决方案,这太过分了。