两种聊天室使用的时同一个客户端
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#define NAME_LEN 48
#define MSG_LEN 1024
int sockfd = -1;
void handle_exit(int sig)
{
close(sockfd);
exit(0);
}
int connect_server(const char *ip, unsigned short port)
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
perror("socket");
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip);
if(connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
perror("connect");
return -1;
}
return sockfd;
}
void *handle_recv(void *arg)
{
while(1)
{
char msg[MSG_LEN] = {};
ssize_t rb = recv(sockfd, msg, MSG_LEN, 0);
if(rb <= 0)
{
perror("recv");
continue;
}
else
{
printf("\r%s\n", msg);
}
}
return NULL;
}
void client_run(const char *ip, unsigned short port)
{
if(signal(SIGINT, handle_exit) == SIG_ERR)
{
perror("signal");
return;
}
sockfd = connect_server(ip, port);
if(sockfd == -1)
{
return;
}
printf("input name:");
char name[NAME_LEN] = {};
scanf("%s", name);
//把'\0'也发送出去
ssize_t wb = send(sockfd, name, strlen(name) + 1, 0);
if(wb <= 0)
{
perror("send");
return;
}
//创建一个线程接收消息
pthread_t pid;
int err = pthread_create(&pid, NULL, handle_recv, NULL);
if(err != 0)
{
perror("pthread_creat");
return;
}
//主线程负责发送消息
while(1)
{
char msg[MSG_LEN] = {};
scanf("%s", msg);
wb = send(sockfd, msg, strlen(msg) + 1, 0);
if(wb <= 0)
{
perror("send");
break;
}
}
}
int main(int argc, char *argv[])
{
client_run(argv[1], atoi(argv[2]));
return 0;
}
多线程并发的服务端
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include