在学习网络编程,于是自己做小项目练手
linux系统下使用基本socket API实现一个简易的聊天室,CS两端能 交互 收发消息
Client:
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;
int main(int argc, char** argv){
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(6666);
char host[20] ={ "127.0.0.1"};
inet_pton(AF_INET,host,&serveraddr.sin_addr);//键入服务器ip
int sockfd = socket(AF_INET,SOCK_STREAM,0);//客户端socket
connect(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));//连接
// 设置/获取超时选项
struct timeval* timeout;
struct timeval stTimeval;
stTimeval.tv_sec = 20;
stTimeval.tv_usec=0;
setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,&stTimeval,sizeof(stTimeval));//设置超时选项
setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&stTimeval,sizeof(stTimeval));
socklen_t *slt = new socklen_t(50);
if(0==getsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,timeout,slt)){//获取超时选项
printf("get success\n");
}
printf("timeout : %d,%d\n",timeout->tv_sec,timeout->tv_usec);
//与服务器轮流收发消息!
char buf[1024];
while(gets(buf)){
string temp = buf;
if(temp=="over"){
printf("welecome next login in our chat room, 88\n");
close(sockfd);
break;
}
write(sockfd,buf,sizeof buf);
int n = read(sockfd,buf,sizeof buf);
if(n>0){
printf("server : %s\n",buf);
}else if (n==0){
printf("passive close\n");
close(sockfd);
break;
}
}
return 0;
}
Server:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
int main(){
int listen_fd = socket(AF_INET,SOCK_STREAM,0);//创建一个socket
struct sockaddr_in serveraddr;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY 泛指本机 0.0.0.0
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(6666);//端口号
bind(listen_fd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));//绑定端口地址
listen(listen_fd,10);//第二个参数是排队的最大连接数
char buf[1024];
int i=1;
while(1){
int connfd = accept(listen_fd,(struct sockaddr*)NULL,NULL);//后面俩参数是返回客户端的信息
if(connfd!=-1){
printf("%dth connect success\n",i);
}
//设置超时信息
struct timeval* timeout;
struct timeval stTimeval;
stTimeval.tv_sec = 20;
stTimeval.tv_usec=0;
setsockopt(connfd,SOL_SOCKET,SO_SNDTIMEO,&stTimeval,sizeof(stTimeval));
setsockopt(connfd,SOL_SOCKET,SO_RCVTIMEO,&stTimeval,sizeof(stTimeval));
while(1){
//connfd是内核为我创建的 与客户通信的 socket
int n = read(connfd,buf,sizeof buf);//返回0 表示读到文件末尾 可以理解为对方数据发送结束
if(n<0){}
else if(n==0){
printf("close %dth connection\n",i);
close(connfd);
break;
}else{
printf("client : %s\n",buf);
gets(buf);
//scanf("%[^\n]",buf);
write(connfd,buf,sizeof buf);
}
}
i++;
}
close(listen_fd);
return 0;
}
compile编译文件
#!/bin/bash
filename=$1
echo ${filename%.*}
g++ -o ${filename%.*} $1 -Wfatal-errors -lpthread -std=c++11
运行截图 注意服务端得先运行