⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simpletalk_server.c

📁 communication with other pc
💻 C
字号:
/*A simple echo server using TCP for part 1*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/utsname.h>


#define SERVER_TCP_PORT 6120 /* server port*/
#define BUFLEN	256	    /* buffer length*/

int main(int argc, char **argv)
{
	int n, bytes_to_read;
	int sd, new_sd, client_len, port;
	struct sockaddr_in server, client;
	char *bp, rbuf[BUFLEN], sbuf[BUFLEN];
	struct utsname name; /*get the information of the machine that runs server  */
	int con = 1;/*continue communicate with client*/
	char quit[BUFLEN] = ".q";
	/*struct hostent *phost;*//*store host information*/
	
	
	switch(argc)
	{
		case 1:
			port = SERVER_TCP_PORT;
			break;
		case 2:
			port = atoi(argv[1]);
			break;
		default:
			fprintf(stderr, "Usage: %s [port]\n", argv[0]);
			exit(1);
	}
	
	/*Create a stream socket*/
	if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		fprintf(stderr, "Can't create a socket\n");
		exit(1);
	}
	
	
	
	
	
	
	
	/*Bind an addr4ess to the socket*/
	bzero((char *) &server ,sizeof(struct sockaddr_in));
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = htonl(INADDR_ANY);
	
	/*print the server name*/
	
	if (uname(&name) == -1)
	{
		fprintf(stderr, "Erro:uname\n");
		exit(1);
	}
	else
	{
		printf("server name is %s\n", name.nodename);
	}
	
	if (bind (sd, (struct sockaddr *) &server, sizeof(server)) == -1)
	{
		fprintf(stderr, "Can't bind name to socket\n");
		exit(1);
	}
	
	/*queue up to  9 connect requests*/
	listen(sd, 5);
	
	while (con)
	{
		client_len = sizeof(client);
		if ((new_sd = accept(sd, (struct sockaddr *)&client, &client_len)) == -1)
		{
			fprintf(stderr, "Can't accept client\n");
			exit(1);
		}
		while(con)
		{
			bp = rbuf;
			bytes_to_read = BUFLEN;
			while (( n = read(new_sd, bp, bytes_to_read)) > 0)
			{
				bp += n;
				bytes_to_read -= n;
				
			}
		
			/*if client input .q then close server and client*/
			if (strcmp(rbuf, quit) == 0)
			{
				
				/*write(new_sd, quit, BUFLEN);*/
				close(new_sd);
				con = 0;/*exit the wait loop*/
			}
			else
			{
				printf("Recieve :\n");
				printf("%s\n", rbuf);
				printf("Transmit :\n");
				fgets(sbuf, BUFLEN, stdin);
				sbuf[strlen(sbuf) - 1] = '\0';
				if (strcmp(sbuf, quit) == 0)
				{
					con = 0;
					write(new_sd, quit, BUFLEN);
					close(new_sd);
				}
				else
				{
					write(new_sd, sbuf, BUFLEN);
				}

			}
		}
	}
	close(sd);
	return(0);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -