#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#define PORT 9996
int socket_fd[2];
void *handl_client(void *v)
{
long i = (long)v;
char buf[1024] = {"asdsadsadsadsa"};
while (1)
{
int ret = read(socket_fd[i], buf, sizeof(buf)-1);
if (-1 == ret)
{
perror ("read error");
break;
}
if (0 == ret)
{
printf ("客户端退出\n");
break;
}
// buf[ret] = '\0';
// printf ("收到客户端数据:%s\n", buf);
// int i;
// for (i = 0; i < ret-1; i++)
// {
// buf[i] += 'A' - 'a';
// }
write(socket_fd[1-i], buf, ret);
}
}
// 监听套接字
int init()
{
int listen_socket = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == listen_socket)
{
perror("创建套接字失败");
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET; /* Internet地址族 */
addr.sin_port = htons(PORT); /* 端口号 */
addr.sin_addr.s_addr = htonl(INADDR_ANY); /* IP地址, 绑定本地的所有ip地址*/
int ret = bind(listen_socket, (const struct sockaddr *)&addr, sizeof(addr));
if(-1 == ret)
{
perror("绑定失败");
return -1;
}
// 3、监听套接字
ret = listen(listen_socket, 5);
if(-1 == ret)
{
perror("监听失败");
return -1;
}
return listen_socket;
}
// 通信套接字
int myAccept(int listen_socket)
{
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_socket = accept(listen_socket, (struct sockaddr *)&client_addr, &len);
if (-1 == client_socket)
{
perror("accept 失败");
return -1;
}
printf ("客户端的 ip = %s, 端口 = %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
return client_socket;
}
// 简单聊天
int main(int argc, char **argv)
{
// 监听套接字
int listen_socket = init();
if (-1 == listen_socket)
return;
long i = 0;
while (i < 2)
{
// 通信套接字
socket_fd[i] = myAccept(listen_socket);
if (-1 == socket_fd[i])
{
continue;
}
// 开辟线程为客户端服务
pthread_t thread;
pthread_create(&thread, NULL, handl_client, (void *)i);
pthread_detach(thread); // 线程分离
i++;
}
close(listen_socket);
pthread_exit(NULL);
return 0;
}
简单聊天
最新推荐文章于 2022-09-02 22:03:12 发布