好友
阅读权限10
听众
最后登录1970-1-1
|
蔚蓝理想
发表于 2020-2-23 14:48
添加libwsock32.a库
添加libws2_32.a能正常编译。
具体哪个忘记了。很多年前写的。用的是dev c++
没有界面。
//客户端
#include <iostream>
#include <Winsock2.h>
#include <Windows.h>
#include <process.h>
using namespace std;
SOCKET client;
void mythread(void * param)
{
char buffer[255];
while(1)
{
if( recv(client,buffer,sizeof(buffer),0) <= 0)
{
printf("对方已断开连接.....");
break;
}
cout << buffer <<endl;
}
}
int main(int argc, char *argv[])
{
WSADATA wData;
WSAStartup( MAKEWORD(2,2), &wData );
client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
char IP[15];
ADD:cout << "请输入服务器IP(如127.0.0.1)..." <<endl;
gets(IP);
sockaddr_in target;
target.sin_family = AF_INET;
target.sin_port = htons (8888);
target.sin_addr.s_addr = inet_addr (IP);
if ( (connect(client, (struct sockaddr*)&target, sizeof(target)) ) == SOCKET_ERROR)
{
printf( "连接服务器错误,请重新输入IP.\n" );
goto ADD;
}
cout << "已成功连接到"<< IP << "可以开始聊天了(*^__^*) "<<endl;
_beginthread(&mythread, 0, NULL);
char message[255];
while(1)
{
gets(message);
send(client,message,sizeof(message),0);
}
system("PAUSE");
return EXIT_SUCCESS;
}
//服务端
#include <iostream>
#include <Winsock2.h>
#include <Windows.h>
#include <process.h>
using namespace std;
SOCKET server, client;
void mythread(void * param)
{
char buffer[255];
while(1)
{
if( recv(client,buffer,sizeof(buffer),0)<=0 )
{
printf("对方已断开连接.....");
break;
}
cout << buffer <<endl;
}
}
int main(int argc, char *argv[])
{
WSADATA wData;
WSAStartup( MAKEWORD(2,2), &wData );
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in localaddr;
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(8888);
localaddr.sin_addr.s_addr = INADDR_ANY;
bind(server, (struct sockaddr*)&localaddr, sizeof(sockaddr));
cout << "等待用户连接..." <<endl;
listen(server,1);
SOCKADDR_IN address;
int size = sizeof( SOCKADDR );
client = accept( server, NULL, NULL );
cout << "用户已连接,可以开始聊天了(*^__^*) ...." <<endl;
_beginthread(&mythread, 0, NULL);
char message[255];
while(1)
{
gets(message);
send(client,message,sizeof(message),0);
}
system("PAUSE");
return EXIT_SUCCESS;
}
|
免费评分
-
查看全部评分
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|