急!C++ 的socket问题!请各位帮帮忙!
下面的代码没有问题,但是我想让服务器端发送一句“连接成功”给客户端,然后客户端打出来,怎么实现?这是客户端代码#include<winsock2.h>#include<s...
下面的代码没有问题,但是我想让服务器端发送一句“连接成功”给客户端,然后客户端打出来,怎么实现?
这是客户端代码
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32")
void main()
{
SOCKET socket1;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested=MAKEWORD(2,2);
WSAStartup(VersionRequested,&WsaData);
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(6020);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
socket1=socket(AF_INET,SOCK_DGRAM,0);
while(1)
{
char buffer[255];
scanf("%s",buffer);
sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&server,sizeof(server));
}
closesocket(socket1);
}
这是服务器端代码
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32")
void main()
{
SOCKET socket1;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested=MAKEWORD(2,2);
WSAStartup(VersionRequested,&WsaData);
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(6020);
server.sin_addr.s_addr=INADDR_ANY;
socket1=socket(AF_INET,SOCK_DGRAM,0);
bind(socket1,(struct sockaddr*)&server,sizeof server);
while(1)
{
char buffer[255];
recvfrom(socket1,buffer,sizeof buffer,0,NULL,NULL);
printf("Received datagram %s\n",buffer);
}
closesocket(socket1);
} 展开
这是客户端代码
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32")
void main()
{
SOCKET socket1;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested=MAKEWORD(2,2);
WSAStartup(VersionRequested,&WsaData);
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(6020);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
socket1=socket(AF_INET,SOCK_DGRAM,0);
while(1)
{
char buffer[255];
scanf("%s",buffer);
sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&server,sizeof(server));
}
closesocket(socket1);
}
这是服务器端代码
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32")
void main()
{
SOCKET socket1;
WORD VersionRequested;
WSADATA WsaData;
VersionRequested=MAKEWORD(2,2);
WSAStartup(VersionRequested,&WsaData);
struct sockaddr_in server;
server.sin_family=AF_INET;
server.sin_port=htons(6020);
server.sin_addr.s_addr=INADDR_ANY;
socket1=socket(AF_INET,SOCK_DGRAM,0);
bind(socket1,(struct sockaddr*)&server,sizeof server);
while(1)
{
char buffer[255];
recvfrom(socket1,buffer,sizeof buffer,0,NULL,NULL);
printf("Received datagram %s\n",buffer);
}
closesocket(socket1);
} 展开
2个回答
展开全部
LZ你这用的是UDP协议,没有connect,所以无法在判断一连接上的时候发送“连接成功”给客户端,不过可以在服务器收到数据的时候(即recvfrom(socket1,buffer,sizeof buffer,0,NULL,NULL);后面)给客户机发送一条信息,然后让客户机进行接收(在 sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&server,sizeof(server)); 后)就行了,同时recvfrom的最后两个参数不可以是NULL
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询