最简单的Linux命令行Socket聊天程序源代码

只有今天贴出代码,明天看才知道自己有多么傻。


单线程,一对一聊天,混搭风格编程,函数乱入不解释……


/*
 * Chat on Linux Terminal--alpha
 * Worte by Jimmy's team@uestc
 * 2011-2-23
 *
 * This is the sorce code of client
 * Some BUGS still unsloved, but we are trying our best to debug
 * Be sure that your system's port "1234" is not busy!
 *
 * */

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define SERVPORT 1234
#define MAX_DATA_SIZE 1024

int main(int argc, char *argv[]) {
	int sockfd, sendBytes,recvBytes;
	char sendBuf[MAX_DATA_SIZE],recvBuf[MAX_DATA_SIZE];
	struct hostent *host;
	struct sockaddr_in servAddr;
	if(argc != 2) {
		fprintf(stderr,"usage:./client [hostname]");
		exit(1);
	}

	/*translate the address*/
	if((host = gethostbyname(argv[1])) == NULL) {
		perror("fail to get host by name");
		exit(1);
	}
	printf("Success to get host by name...\n");

	/*establish a socket*/
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("fail to establish a socket");
		exit(1);
	}
	printf("Success to establish a socket...\n");
	
	/*init sockaddr_in*/
	servAddr.sin_family = AF_INET;
	servAddr.sin_port = htons(SERVPORT);
	servAddr.sin_addr = *((struct in_addr *)host -> h_addr);
	bzero(&(servAddr.sin_zero), 8);

	/*connect the socket*/
	if(connect(sockfd, (struct sockaddr *)&servAddr, sizeof(struct sockaddr_in)) == -1) {
		perror("fail to connect the socket");
		exit(1);
	}
	printf("Success to connect the socket...\n");
	printf("\033[40;32mWelcome to join %s!\033[1m\n", inet_ntoa(servAddr.sin_addr));	//include color set

	while(1) {
		/*send datas to server*/
		printf("Client:");
		gets(sendBuf);
		if((sendBytes = send(sockfd, sendBuf, strlen(sendBuf), 0)) != strlen(sendBuf)) {
			perror("fail to send datas");
			exit(1);
		}
		printf("(Success to send data!)\n");
		memset(sendBuf, 0x00, MAX_DATA_SIZE);

		/*receive datas from server*/
		if((recvBytes = recv(sockfd, recvBuf, MAX_DATA_SIZE, 0)) == -1) {
			perror("fail to receive datas");
			exit(1);
		}
		printf("Server: %s \n", recvBuf);
		memset(recvBuf, 0x00, MAX_DATA_SIZE);
	}
	close(sockfd);
}


/*
 * Chat on Linux Terminal--alpha
 * Worte by Jimmy's team@uestc
 * 2011-2-23
 *
 * This is the sorce code of server
 * Some BUGS still unsloved, but we are trying our best to debug
 * Be sure that your system's port "1234" is not busy!
 *
 * */

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/time.h>
#include<sys/un.h>
#include<sys/ioctl.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define SERVPORT 1234
#define BACKLOG 20
#define MAX_CON_NO 10
#define MAX_DATA_SIZE 1024

int main(int argc, char *argv[]) {
	struct sockaddr_in serverSockaddr, clientSockaddr;
	int sinSize, recvBytes, sendBytes;
	fd_set readfd;
	fd_set writefd;
	int sockfd, clientfd;
	char sendBuf[MAX_DATA_SIZE], recvBuf[MAX_DATA_SIZE];

	if(argc != 1) {
		printf("usage:./server\n");
		exit(1);
	}

	/*establish a socket*/
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("fail to establish a socket");
		exit(1);
	}
	printf("Success to establish a socket...(sockfd = %d)\n", sockfd);

	/*init sockaddr_in*/
	serverSockaddr.sin_family = AF_INET;
	serverSockaddr.sin_port = htons(SERVPORT);
	serverSockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	bzero(&(serverSockaddr.sin_zero), 8);
	
	int on = 1; 
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	/*bind socket*/
	if(bind(sockfd, (struct sockaddr *)&serverSockaddr, sizeof(struct sockaddr))== -1) {
		perror("fail to bind");
		exit(1);
	}
	printf("Success to bind the socket...\n");


	/*listen on the socket*/
	if(listen(sockfd, BACKLOG) == -1) {
		perror("fail to listen");
		exit(1);
	}
	printf("Success to listen on the socket...\n");

	while(1) {
		FD_ZERO(&readfd);
		FD_SET(sockfd, &readfd);
		sinSize = sizeof(struct sockaddr_in);
		if(select(MAX_CON_NO, &readfd, NULL, NULL, (struct timeval *)0) > 0) {
			if(FD_ISSET(sockfd, &readfd) > 0) {

				/*accept a client's request*/
				if((clientfd = accept(sockfd, (struct sockaddr *)&clientSockaddr, &sinSize)) == -1) {
					perror("fail to accept");
						exit(1);
				}
				printf("Success to accpet a connection request...\n");
				printf("\033[40;32m%s join in!\033[1m\n", inet_ntoa(clientSockaddr.sin_addr));//include color set
			
				while(1) {
					/*receive datas from client*/
					if((recvBytes = recv(clientfd, recvBuf, MAX_DATA_SIZE, 0)) == -1) {
						perror("fail to receive datas");
						exit(1);
					}
					printf("Client:%s\n", recvBuf);
					memset(recvBuf, 0x00, MAX_DATA_SIZE);
				
					/*send datas to client*/
					printf("Server:");
					gets(sendBuf);
					if((sendBytes = send(clientfd, sendBuf, strlen(sendBuf), 0)) != strlen(sendBuf)) {
						perror("fail to send datas");
						exit(1);
					}
					printf("(Success to send data!)\n");
					memset(sendBuf, 0x00, MAX_DATA_SIZE);
				}
			}
			close(sockfd);
		}
	}
}

运行方法:

jimmy@MyPet:~$ gcc -o client client.c 
jimmy@MyPet:~$ gcc -o server server.c 
jimmy@MyPet:~$ ./server 
Success to establish a socket...(sockfd = 3)
Success to bind the socket...
Success to listen on the socket...

jimmy@MyPet:~$ ./client MyPet
Success to get host by name...
Success to establish a socket...
Success to connect the socket...
Welcome to join 127.0.1.1!
Client:



  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个简单Linux 聊天程序的生成代码,其中使用了 socket 和 pthread 库: server.c ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pthread.h> #define PORT 8888 #define MAX_CLIENTS 100 int clients[MAX_CLIENTS]; int num_clients = 0; void *handle_client(void *arg) { int client_fd = *(int *) arg; char buffer[1024]; while (1) { memset(buffer, 0, sizeof(buffer)); if (read(client_fd, buffer, sizeof(buffer)) <= 0) { printf("Client %d disconnected\n", client_fd); break; } printf("Received message from client %d: %s", client_fd, buffer); for (int i = 0; i < num_clients; i++) { if (clients[i] != client_fd) { write(clients[i], buffer, strlen(buffer)); } } } for (int i = 0; i < num_clients; i++) { if (clients[i] == client_fd) { clients[i] = clients[num_clients - 1]; num_clients--; break; } } close(client_fd); return NULL; } int main(int argc, char *argv[]) { int server_fd, client_fd; struct sockaddr_in server, client; pthread_t thread; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(EXIT_FAILURE); } server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(PORT); if (bind(server_fd, (struct sockaddr *) &server, sizeof(server)) == -1) { perror("bind"); exit(EXIT_FAILURE); } if (listen(server_fd, 5) == -1) { perror("listen"); exit(EXIT_FAILURE); } printf("Server started\n"); while (1) { socklen_t client_len = sizeof(client); if ((client_fd = accept(server_fd, (struct sockaddr *) &client, &client_len)) == -1) { perror("accept"); continue; } if (num_clients == MAX_CLIENTS) { printf("Maximum number of clients reached\n"); close(client_fd); continue; } clients[num_clients++] = client_fd; pthread_create(&thread, NULL, handle_client, (void *) &client_fd); pthread_detach(thread); printf("Client %d connected\n", client_fd); } return 0; } ``` client.c ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #define SERVER_IP "127.0.0.1" #define PORT 8888 int main(int argc, char *argv[]) { int server_fd; struct sockaddr_in server; char buffer[1024]; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(EXIT_FAILURE); } server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(SERVER_IP); server.sin_port = htons(PORT); if (connect(server_fd, (struct sockaddr *) &server, sizeof(server)) == -1) { perror("connect"); exit(EXIT_FAILURE); } printf("Connected to server\n"); while (1) { fgets(buffer, sizeof(buffer), stdin); if (write(server_fd, buffer, strlen(buffer)) == -1) { perror("write"); exit(EXIT_FAILURE); } } return 0; } ``` 以上代码可以在 Linux 系统下编译运行,实现一个简单聊天程序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值