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

📄 server.c

📁 linux下的聊天程序
💻 C
字号:
//server.c
//#include <stdio.h> 
//#include <winsock2.h> 
//#include <string.h> 
//#include <conio.h> 
#include "../lib/myinclude.h"
//#define INVALID_SOCKET (int)(~0)   //#define INVALID_SOCKET -1
/* 定义变量 */
int server,client; 
//WSADATA WSAData; 
int sockfd;
struct sockaddr_in local,from; 
int fromlen = sizeof(from); 
char information[50]; 
char welcome[] = "Wellcom you!\n"; 
char receive[256]; 
char ip[] = "your IP is:"; 
char chat[256]; 
char c; 
int i = 0; 
int cansend = 0; 
/* 得到IP地址 */
int GetIp() 
{ 
	bzero(&local,sizeof(local));
	local.sin_family = AF_INET; 
             //AF_INET是地址族(Address Family);PF_INET是协议族(Protocol Family)
        local.sin_addr.s_addr = htonl(INADDR_ANY); 
        //INADDR_ANY 的具体含义是,绑定到0.0.0.0。此时,对所有的地址都将是有效的
        local.sin_port = htons(SERV_PORT); 
         //端口号要从一个16位无符号数(u_short类型数)从主机字节顺序转换成网络字节顺序,/用htons()函数。
        server = socket(AF_INET,SOCK_STREAM,0); 
        if(server == -1){ 
		printf("Cannot create socket!\n");
		return 0; 
	}
	if(bind(server,(struct sockaddr *)&local,sizeof(local))!=0){
		printf("Cannot bind socket!\n");
		return 0; 
	} 

	if(listen(server,5)!=0){
		printf("Cannot listening port!\n"); 
		return 0; 
	}
	while(1){
		printf("waitting for user connect...\n"); 
		client = accept(server,(struct sockaddr *)&from,&fromlen);
		strcpy(information,inet_ntoa(from.sin_addr)); 
		strcat(welcome,information);
		printf("accept %s connect...\n",inet_ntoa(from.sin_addr)); 
		printf("send wellcome message...\n");
		send(client,welcome,strlen(welcome),0);
		              //send(client,ip,strlen(ip),0); 
                              //send(client,information,strlen(information),0); 
		printf("wellcome message send to client successed!\n"); 

		while(1){
			if(!cansend) {
				printf("waitting for the message...\n"); 
				cansend = 0;
				recv(client,receive,sizeof(receive),0);
				printf("***** message received *****\n");
				printf("%s\n",receive);
				printf("***** END *****\n");
				cansend = 1;
			}
			else {
				printf("Please enter next message:");
				scanf("%s\0",&chat);
				send(client,chat,strlen(chat),0);
				printf("\nmessage send successed!\n");
				cansend = 0;
			}
		}// end_while(1)
		closesocket(client); 
	}// end_while(true)
	closesocket(server);
	return 1;
} 
/////////////服务器主程序///////////////////
int main() 
{
	int ok;
	ok = GetIp();
	if(ok == 0) 
		printf("Do the request failed!\n");
	getchar();    //getch()函数用途:从控制台读取一个字符,但不显示在屏幕上 
} 

⌨️ 快捷键说明

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