求C++,socket聊天程序的代码,最好是实现了两个客户端之间经由服务器的信息互发,聊天功能要完整些

代码格式要清晰一些。谢谢了。7.9.4.2.5.8.1.1.0.@q.q.com... 代码格式要清晰一些。谢谢了。7.9.4.2.5.8.1.1.0.@q.q.com 展开
 我来答
百度网友5e91607da
2013-05-05 · 超过28用户采纳过TA的回答
知道答主
回答量:96
采纳率:100%
帮助的人:44.6万
展开全部
#include <stdio.h>
#include <winsock2.h>
#define MAX_SIZE 200
void main(void) {
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return;
}

SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
SOCKADDR addrClient;
char recvBuffer[MAX_SIZE];
memset(recvBuffer, 0, sizeof(recvBuffer));
int len = sizeof(SOCKADDR);
recvfrom(sockSrv, recvBuffer, sizeof(recvBuffer), 0, (SOCKADDR *)&addrClient, &len);

printf("%s\n", recvBuffer);
closesocket(sockSrv);
}
#include <stdio.h>
#include <winsock2.h>
void main(void) {
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */

if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return;
}

/* The WinSock DLL is acceptable. Proceed. */

SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrClient;
addrClient.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrClient.sin_family = AF_INET;
addrClient.sin_port = htons(6000);
sendto(sockClient, "你若此生若只如一瞬", strlen("你若此生若只如一瞬"), 0, (SOCKADDR *)&addrClient, sizeof(SOCKADDR));
closesocket(sockClient);
WSACleanup();
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式