//
转载网络聊天程序
//server端代码如下
#include<stdio.h>
#include<winsock2.h>
#include<string.h>
#include<conio.h>
SOCKET server;
SOCKET client;
WSADATA WSAData;
int WSAreturn;
sockaddr_in local;
sockaddr_in from;
int fromlen = sizeof(from);
char information[50];
char welcome[]="欢迎您登陆YYJW主机!\n";
char receive[256];
char ip[]="您的IP是:";
char chat[256];
char c;
int i=0;
bool cansend=false;
int GetIp()
{
WSAreturn = WSAStartup(0x101,&WSAData);
if(WSAreturn)
{
printf("发生一个未知错误!\n");
return 0;
}
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = htons((u_short)23);
server = socket(AF_INET,SOCK_STREAM,0);
if(server==INVALID_SOCKET )
{
printf("无法创建套接字!\n");
return 0;
}
if(bind(server,(sockaddr *)&local,sizeof(local))!=0)
{
printf("无法绑定套接字!\n");
return 0;
}
if(listen(server,5)!=0)
{
printf("无法监听端口!\n");
return 0;
}
while(true)
{
printf("正在等待用户连接...\n");
client = accept(server,(struct sockaddr *)&from,&fromlen);
strcpy(information,inet_ntoa(from.sin_addr));
strcat(welcome,information);
printf("接受来自%s的连接...\n",inet_ntoa(from.sin_addr));
printf("正在发送欢迎消息...\n");
send(client,welcome,strlen(welcome),0);
//send(client,ip,strlen(ip),0);
//send(client,information,strlen(information),0);
printf("欢迎消息信息已经成功发送至客户端!\n");
while(1)
{
if(!cansend)
{
printf("正在等待对方发来消息...\n");
cansend=false;
recv(client,receive,sizeof(receive),0);
printf("*********接受到的消息***********\n");
printf("%s\n",receive);
printf("**************结束**************\n");
cansend=true;
}
else
{
printf("请输入下一条消息:");
scanf("%s\0",&chat);
send(client,chat,strlen(chat),0);
printf("\n已经成功发送出信息!\n");
cansend=false;
}
}
closesocket(client);
}
closesocket(server);
WSACleanup();
return 1;
}
void main()
{
int ok;
ok = GetIp();
if(ok==0)
printf("无法完成请求!\n");
getch();
}