好久没写c 晚上写了个聊天室温习下
服务端
/*
* server.c
* 请直接将本代码复制粘贴到你的编译环境中,编译且运行.
* 运行后,可在浏览器中输入地址http://127.0.0.1/来访问server.
* */
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#pragma comment(lib , "Ws2_32.lib")
int main( int argc , char* argv[])
{
char msg[1000];
int serverSock , connectingSock;
struct sockaddr_in serverAddr, client_addr;
socklen_t addrlen , client_addr_size;
serverSock = socket( AF_INET , SOCK_STREAM , IPPROTO_TCP);
if( serverSock <0)
{
puts("socket建立失败");
exit(1);
}
addrlen = sizeof(serverAddr);
memset( &serverAddr , 0 , addrlen);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(3333);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if( bind( serverSock , (struct sockaddr*)&serverAddr , sizeof(serverAddr) )<0)
{
puts("绑定IP 地址到socket失败");
exit(1);
}
if(listen( serverSock , 10 ))
{
puts("设置socket为监听状态失败");
}
puts("等待客户端连接...");
client_addr_size = sizeof(client_addr);
connectingSock = accept( serverSock , (struct sockaddr*)&client_addr , &client_addr_size);
if( connectingSock <0 )
{
puts("处理连接时发生错误");
}
puts("发送一个心跳");
char sg[2] = "ss";
if( send( connectingSock , sg, sizeof(sg) , 0) <=0 )
{
puts("发送消息失败");
}else{
puts("发送消息成功");
}
while(1){
memset( msg , 0 , 1000) ;
if ( recv( connectingSock , msg , 999 , 0) <= 0 )
{
puts("接收消息失败");
}else{
puts( msg);
}
char send_msg[200] ;
puts("请输入聊天内容");
scanf("%s", send_msg);
if( send( connectingSock , send_msg, strlen(send_msg ) , 0) <=0 )
{
puts("发送消息失败");
}else{
puts("发送消息成功");
}
}
}
客户端:
/*
* server.c
* 请直接将本代码复制粘贴到你的编译环境中,编译且运行.
* 运行后,可在浏览器中输入地址http://127.0.0.1/来访问server.
* */
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#pragma comment(lib , "Ws2_32.lib")
void error_handling(char *message);
int main( int argc , char* argv[])
{
char msg[1000];
int client_sock ;
struct sockaddr_in client_addr ,server_addr;
int addrlen, strlen ;
char message[20];
client_sock = socket( AF_INET , SOCK_STREAM , IPPROTO_TCP);
if( client_sock <0)
{
puts("socket建立失败");
exit(1);
}
puts("socket成功建立");
addrlen = sizeof(client_addr);
memset( &client_addr , 0 , addrlen);
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(3333);
client_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(client_sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) == -1)
error_handling("connect error");
while(1){
memset( msg , 0 , 1000) ;
if ( recv( client_sock , msg , 999 , 0) <= 0 )
{
puts("接收消息失败");
}else{
puts( msg);
}
char send_msg[200] ;
puts("请输入聊天内容");
scanf("%s", send_msg);
if( send( client_sock , send_msg, sizeof(send_msg) , 0) <=0 )
{
puts("发送消息失败");
}else{
puts("发送消息成功");
}
}
//return 0;
}
void error_handling(char * message){
puts(message);
exit(1);
}