我想在LAN中制作服务器-客户端程序。我正在使用0.0.0.0打开服务器。我的iPv4地址是192.168.1.3。我正在尝试连接到服务器。我不确定客户端是否无法连接到服务器或服务器是否不接受请求。
即使关闭WINDOWS DEFENDER,我也没有任何通信。我在服务器计算机上打开一个端口,当我在服务器计算机的cmd中写入“ netstat -a”时,我可以看到7700监听。但是当我在客户端计算机的cmd中写入“ netstat -a”时,我看不到7700监听。
//MY SERVER
#include <iostream>
#include<ws2tcpip.h>
using namespace std;
int main(){
cout<<"SERVER"<<endl;
WSADATA x;
WSAStartup(MAKEWORD(2,2),&x);
SOCKET server;
server=socket(AF_INET,SOCK_STREAM,0);
if(server==INVALID_SOCKET){
cout<<"-socket"<<endl;
}
struct sockaddr_in adres;
adres.sin_port=htons(7700);
adres.sin_family=AF_INET;
adres.sin_addr.s_addr=inet_addr("0.0.0.0");
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
int b=bind(server,(struct sockaddr*)&adres,sizeof(adres));
if(b==-1){
cout<<"-bind"<<endl;
}
int l=listen(server,4);
if(l==-1){
cout<<"-listen"<<endl;
}
struct sockaddr_in client;
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
int sizq=sizeof(client);
SOCKET c=accept(server,(struct sockaddr*)&client,&sizq);
if(c==INVALID_SOCKET){
cout<<"-accept"<<endl;
}
char name[100];
int pr=recv(c,name,100,0);
if(pr==-1){
cout<<"-name take"<<endl;
}
cout<<name<<" connected."<<endl;
char msg[100];
while(1){
int r=recv(c,msg,100,0);
if(r==-1){
for(int q=6;1;q--){
cout<<name<<" disconnected ("<<q<<")"<<endl;
Sleep(1000);
if(q==0){
break;
}
}
break;
}
cout<<name<<":"<<msg<<endl;
}
closesocket(server);
WSACleanup();
return 0;
}
//CLİENT
#include<iostream>
#include<winsock2.h>
#include<windows.h>
#include<ws2tcpip.h>
#include<string.h>
#include<string>
#include <stdio.h>
using namespace std;
int main(){
WSADATA ab;
WSAStartup(MAKEWORD(2,2),&ab);
cout<<"CLIENT"<<endl;
SOCKET server;
server=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in as;
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
as.sin_addr.s_addr=inet_addr("192.168.1.3");
as.sin_family=AF_INET;
as.sin_port=htons(7700);
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
SOCKET b=connect(server,(struct sockaddr*)&as,sizeof(as));
char name[100];
gethostname(name,100);
send(server,name,100,0);
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
char msg[100];
while(1){
cout<<"Mesaj:";
cin>>msg;
send(server,msg,100,0);
if(GetLastError()!=0){
cout<<GetLastError()<<endl;
}
}
closesocket(server);
WSACleanup();
return 0;
}