2 christophe123 CHRISTOPHE123 于 2016.03.20 14:48 提问

套接字程序,可以和本机的服务器互联,不能连接别的服务器,error10057,求大神帮忙! 5C

下面是代码:

 /* TCPClient.cpp  -- 用于传递struct */
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <math.h>
#define BUFLEN      2000                  // 缓冲区大小
#define WSVERS      MAKEWORD(2, 0)        // 指明版本2.0 
#pragma comment(lib,"ws2_32.lib")         // 指明winsock 2.0 Llibrary

/*------------------------------------------------------------------------
* main - TCP client for DAYTIME service
*------------------------------------------------------------------------*/

SOCKET  sock, sockets[100] = { NULL };   /* socket descriptor           */                                                          //  int cc;                             /* recv character count         */
char    *packet = NULL;             /* buffer for one line of text  */
char *pts, *input;
HANDLE hThread;
unsigned threadID;

unsigned int __stdcall Chat(PVOID PM) {
    time_t  now;
    (void)time(&now);
    pts = ctime(&now);
    char buf[2000];
    while (1) {
        int cc = recv(sock, buf, BUFLEN, 0);   //cc为接收的字符数
        if (cc == SOCKET_ERROR || cc == 0) {
            printf("Error: %d ", GetLastError());
            printf("与服务器断开连接!\n");
            (void)closesocket(sock);
            break;
        }
        else if (cc > 0) {
            buf[cc] = '\0';
            printf("%s\n", buf);
        }
    }
    return 0;
}
int main(int argc, char *argv[]) {
    time_t  now;
    (void)time(&now);
    pts = ctime(&now);
    //char  *host = "192.168.220.1"; /* server IP to connect         */
    //char *host = "192.168.220.1";
    char *host = "202.116.76.22";
    char *service = "5050";         /* server port to connect       */
    struct  sockaddr_in sin;            /* an Internet endpoint address */
    WSADATA wsadata;
    WSAStartup(WSVERS, &wsadata);       /* 启动某版本Socket的DLL        */
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons((u_short)atoi(service));    //atoi:把ascii转化为int. htons:主机序(host)转化为网络序(network), s--short
    sin.sin_addr.s_addr = inet_addr(host);           //如果host为域名,需要先用函数gethostbyname把域名转化为IP地址
    sock = socket(PF_INET, SOCK_STREAM, 0);
    hThread = (HANDLE)_beginthreadex(NULL, 0, Chat, NULL, 0, &threadID);
    printf("                             LET'S CHAT(CLIENT)\n");
    connect(sock, (struct sockaddr *)&sin, sizeof(sin));
    while (1) {
        printf("请输入您要发送的信息:\n");
        char buf1[2000];
        gets_s(buf1);
        if (!strcmp(buf1, "exit"))
            goto end;
        (void)send(sock, buf1, sizeof(buf1), 0);
        (void)time(&now);
        pts = ctime(&now);
        printf("发送成功!\n当前时间:%s\n", pts);
    }

end:
    CloseHandle(hThread);
    closesocket(sock);
    WSACleanup();                     /* 卸载某版本的DLL */
    printf("按回车键继续...");
    getchar();
    return 0;                          /* exit */
}

下面是服务器代码:

 /* TCPServer.cpp - main */

#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#include "conio.h"
#include<windows.h>
#include<process.h>
#include<math.h>
#define QLEN       5
#define WSVERS  MAKEWORD(2, 0)
#define BUFLEN 2000
#pragma comment(lib,"ws2_32.lib")  //使用winsock 2.2 library
/*------------------------------------------------------------------------
* main - Iterative TCP server for TIME service
*------------------------------------------------------------------------
*/
SOCKET msock, ssock;
SOCKET sockets[100] = { NULL };
int cc;
char *pts;
time_t now;
char buf[2000];           //buffer
char *input;
HANDLE hThread1, hThread[100] = { NULL };
unsigned int threadID, ThreadID[100], number;
struct sockaddr_in fsin;
struct sockaddr_in Sin;

unsigned int __stdcall Chat(PVOID PM) {
    char buf1[2000] = { NULL };
    char buf2[2000] = { NULL };
    char buf3[2000] = { NULL };
    char buf4[2000] = { NULL };

    /*char buf1[2000]; 
    char buf2[2000]; 
    char buf3[2000]; 
    char buf4[2000]; */

    (void)time(&now);
    pts = ctime(&now);
    sockets[number] = ssock;
    SOCKET sock = ssock;
    ThreadID[number] = threadID;
    unsigned int threadid = threadID;
    sprintf(buf1, "线程号:[%d] 当前时间:%s", threadid, pts);
    (void)send(sock, buf1, sizeof(buf1), 0);
    sprintf(buf2, "线程号:[%d] 客户IP:[%d] 端口:[%d] enter!\n", threadid, inet_ntoa(Sin.sin_addr), fsin.sin_port);
    printf("%s", buf2);
    printf("数据已传送到所有用户!\n");
    for (int i = 0; i <= number; i++) {
        if (sockets[i] != NULL&& sockets[i] != sock) {
            (void)send(sockets[i], buf2, sizeof(buf2), 0);
            printf("发送至线程号[%d]成功! \n", ThreadID[i]);
        }
    }
    printf("\n");

flag1:
    cc = recv(sock, buf3, BUFLEN, 0);
    if (cc == SOCKET_ERROR || cc == 0) {
        (void)time(&now);
        pts = ctime(&now);
        sprintf(buf3, "线程号:[%d] 客户IP:[%d] 端口:[%d] leave !\n当前时间:%s", threadid, inet_ntoa(Sin.sin_addr), fsin.sin_port, pts);
        sock = NULL;
        sockets[number] = NULL;
        printf("%s", buf3);
        printf("数据已传送到所有用户!\n");
        for (int i = 0; i <= number; i++) {
            if (sockets[i] != NULL && sockets[i] != sock) {
                (void)send(sockets[i], buf3, sizeof(buf3), 0);
                printf("发送至线程号[%d]成功 !\n", ThreadID[i]);
            }
        }
        printf("\n");
    }

    else if (cc > 0) {
        (void)time(&now);
        pts = ctime(&now);
        sprintf(buf4, "线程号:[%d] IP:[%d] 端口:[%d] \n消息内容:%s;\n当前时间:%s", threadid, inet_ntoa(Sin.sin_addr), fsin.sin_port, buf3, pts);
        printf("%s", buf4);
        printf("数据已传送到所有用户!\n");
        for (int i = 0; i <= number; i++) {
            if (sockets[i] != NULL&&sockets[i] != sock) {
                (void)send(sockets[i], buf4, sizeof(buf4), 0);
                printf("发送至线程号[%d]成功!\n", ThreadID[i]);
            }
        }
        printf("\n");
        goto flag1;
    }
    (void)closesocket(sock);
    return 0;
}


void main(int argc, char *argv[]) {
    int     alen;                                         /* from-address length*/
    WSADATA wsadata;
    char    *service = "5050";
    WSAStartup(WSVERS, &wsadata);                         //加载 winsock 2.2 library
    msock = socket(PF_INET, SOCK_STREAM, 0);              //生成套接字。TCP协议号=6, UDP协议号=17
    memset(&Sin, 0, sizeof(Sin));
    Sin.sin_family = AF_INET;
    Sin.sin_addr.s_addr = INADDR_ANY;                    //指定绑定接口的IP地址。INADDR_ANY表示绑定(监听)所有的接口。
    Sin.sin_port = htons((u_short)atoi(service));        //atoi--把ascii转化为int,htons - 主机序(host)转化为网络序(network), s(short) 
    bind(msock, (struct sockaddr *)&Sin, sizeof(Sin));   // 绑定端口号(和IP地址)
    listen(msock, 5);                                    //队列长度为5
    printf("                             LET'S CHAT (SERVER) \n");
    (void)time(&now);   pts = ctime(&now);
    printf("当前时间:%s", pts);
    number = -1;
    while (1) {                                    //检测是否有按键
        alen = sizeof(struct sockaddr);
        ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
        number++;
        hThread[number] = (HANDLE)_beginthreadex(NULL, 0, Chat, NULL, 0, &threadID);
    }
    (void)closesocket(msock);
    WSACleanup();                         //卸载载 winsock 2.2 library
}

3个回答

bealing
bealing   Rxr 2016.03.20 16:24

先ping一下主机,看能不能ping通咯

CHRISTOPHE123
CHRISTOPHE123 这个是我的IPchar *host = "192.168.220.1"; 这是老师提供的测试地址 char *host = "202.116.76.22"; 刚刚发现可以连的上,可是一连上就会退出,不能进行后面的输入输出操作,但在本机上是可以的,是不是我的代码错了,但改了半天也没结果
一年多之前 回复
bealing
bealing 服务器的IP地址和客户端的IP地址,在一个网段吗?也就是说你客户端的IP地址是202.116.76.22这种形式吗,还是192.168.220.n
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 回复Bealing: 都是校园网啊
一年多之前 回复
bealing
bealing 如果你的主机在局域网内,然后你用客户端连外网,一般是连不上的
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 回复Bealing: 学校的,发错了
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 回复Bealing: 局域网,学习的
一年多之前 回复
bealing
bealing 我没发现什么错误,局域网测试时成功的,外网没有环境测试不了。。。。。。 你ping的IP是局域网的还是外网的?
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 大神,你还在吗?
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 回复Bealing: 服务器代码也弄出来了
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 回复Bealing: 好的
一年多之前 回复
bealing
bealing 回复修川地藏: 检查一下是不是端口被占用,顺便把服务器代码贴出来,帮你检查下
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123 可以啊
一年多之前 回复
CHRISTOPHE123
CHRISTOPHE123   2016.03.20 18:01

图片说明
图片说明
图片说明

lyhoo163
lyhoo163   Rxr 2016.03.21 07:16

本机能连接,说明套拼字正确。
问题出在网络连接上:
(1)取消服务器防火墙;
(2)建议服务器使用静态IP地址
(3)服务器端相关网络的参数设置有问题。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!