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

📄 server.c

📁 socket, server.c and client.c
💻 C
字号:
/**************************************************************** * $ID: server.c        三, 26  3月 2008 15:36:59 +0800  root $ * *                                                              * * Description:                                                 * *                                                              * * Maintainer:  范美辉(Meihui Fan)  <mhfan@hhcn.com>            * *                                                              * * Copyright (C)  2008  HHTech                                  * *   www.hhcn.com, www.hhcn.org                                 * *   All rights reserved.                                       * *                                                              * * This file is free software;                                  * *   you are free to modify and/or redistribute it   	        * *   under the terms of the GNU General Public Licence (GPL).   * *                                                              * * Last modified: 三, 26  3月 2008 17:00:53 +0800       by root # ****************************************************************/#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#define PORT	4000#define BACKLOG	10int main(int argc, char *argv[]){    int sock_fd, new_fd;    int sin_size;    struct sockaddr_in server_addr, client_addr;    char welcome[50];    int opt = 1;    int len = sizeof(opt);    char buf[100];    if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)    {	perror("socket");	exit(1);    }    setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &opt, &len);    server_addr.sin_family = AF_INET;    server_addr.sin_port = htons(PORT);    server_addr.sin_addr.s_addr = INADDR_ANY;    bzero(&(server_addr.sin_zero), 8);    if(bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)    {	perror("bind");	close(sock_fd);	exit(1);    }    if(listen(sock_fd, BACKLOG) == -1)    {	perror("listen");	close(sock_fd);	exit(1);    }    while(1)    {	sin_size = sizeof(struct sockaddr_in);	if((new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size)) == -1)	{	    perror("accept");	    continue;	}	printf("server got connection from %s\n", inet_ntoa(client_addr.sin_addr));	snprintf(&welcome[0], 50, "Welcome connect to %s测试\n", inet_ntoa(server_addr.sin_addr));	send(new_fd, &welcome[0], 50, 0);	while(1)	{	    recv(new_fd, &buf[0], 100, 0);	    printf("receive => %s\n", &buf[0]);	    printf("send => ");	    while((fgets(&buf[0], 100, stdin)) == NULL);	    send(new_fd, &buf[0], 100, 0);	}		close(sock_fd);	return 0;    }}/******************** End Of File: server.c ********************/// vim:sts=4:ts=8: 

⌨️ 快捷键说明

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