我写的socket程序,在自己一台机器上可以通话,链到局域网不能连接,请问原因
首先,问题不是在127.0.0.1上,换IP也不能在2台机器上1个是client端 1个是service端
cpp文件在附件中
service:
程序代码:
#include<iostream.h> #include<winsock2.h> //winsock头文件 #pragma comment(lib,"ws2_32.lib") //winsock库 void main() { //调用WSAStartup初始化Winsock库 WSADATA wsaData; ::WSAStartup( MAKEWORD(2,0), //版本号为2.2 &wsaData); //WSADATA结构体 //创建套接字sService,用来等待客户到来的监听链接 SOCKET sService = socket( AF_INET, //协议族 SOCK_STREAM, //tcp流 0); cout<<"create socket successful !"<<endl; //调用bind()绑定端口和地址 sockaddr_in sctaddr; sctaddr.sin_family = AF_INET; //协议族,Winsock中必须为AF_INET sctaddr.sin_port = htons(8080); //bind端口 sctaddr.sin_addr.S_un.S_addr = inet_addr("219.245.96.165"); //本地任意IP地址 bind( sService, //套接字 (sockaddr*)&sctaddr, //绑定的地址 sizeof(sockaddr)); //地址结构大小 cout<<"bind socket successful !"<<endl; //调用listen()开始监听 listen( sService, 2); //可以链接的最大客户端数量 cout<<"listen socket successful !"<<endl; sockaddr_in addrremote; //远程地址 int nLen = sizeof(addrremote); //sockaddr_in结构长度 //调用accept()接受新链接,得到新客户端套接字sClient SOCKET sClient = accept( sService, //监听的服务器套接字 (sockaddr*)&addrremote, //远程客户端地址 &nLen); //接受地址结构大小 cout<<"accept socket successful !"<<endl; while(1) { //调用send() recv()收发信息 char bufrecv[1024] = {0}; recv( sClient, //客户端套接字 bufrecv, //接受数据缓冲区 sizeof(bufrecv), //buf大小 0); //打印收到的消息 cout<<bufrecv<<endl; char bufsend[1024] = {0}; cout<<"Service:"; cin>>bufsend; cout<<endl; send( sClient, bufsend, //发送内容 sizeof(bufsend), //发送内容大小 0); } //关闭套接字 closesocket(sClient); //关闭服务器监听套接字 closesocket(sService); WSACleanup(); }
client端:
程序代码:
#include<iostream.h> #include<winsock2.h> //winsock头文件 #pragma comment(lib,"ws2_32.lib") //winsock库 void main() { //调用WSAStartup初始化Winsock库 WSADATA wsaData; ::WSAStartup( MAKEWORD(2,0), //版本号为2.2 &wsaData); //WSADATA结构体 //创建套接字sListen,用来等待客户到来的监听链接 SOCKET sClient = socket( AF_INET, //协议族 SOCK_STREAM, //tcp流 0); //调用connect()链接到服务器 sockaddr_in addrService; addrService.sin_family = AF_INET; //协议族 addrService.sin_port = htons(8080); //端口 addrService.sin_addr.S_un.S_addr = inet_addr("219.245.96.165"); //服务器IP地址 connect( sClient, //客户端套接字 (sockaddr*)&addrService, //服务器端地址 sizeof(sockaddr)); //地址结构大小 while(1) { //调用send() recv()收发信息 send( sClient, "I am Client,I connect you", sizeof("I am Client,I connect you"), 0); char bufrecv[1024] = {0}; recv(sClient, bufrecv, sizeof(bufrecv), 0); cout<<bufrecv<<endl; } //关闭套接字 closesocket(sClient); WSACleanup(); }