Linux课程设计(2)

2019-03-23 12:15

2)发送功能

3. 服务器端功能模块(Server)

服务器端,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

3.代码实现

(1)客户端代码

#include #include #include #include #include #include #include #include

#define TRUE 1 #define PORT 1000

static int sockfd;

void recvfromserver() //接受服务器消息线程入口函数 { char mes[1024]; int nbytes=0;

while(1) { memset(mes,0,sizeof(mes)); nbytes=read(sockfd,mes,sizeof(mes)); if(nbytes>0) { mes[nbytes]='\\0'; printf(\

}

}

pthread_exit(NULL);

}

int main(int argc, char *argv[]) {

// int sockfd; char buffer[1024];

struct sockaddr_in server_addr; struct hostent *host; int portnumber,nbytes; char *strhost=\ char clientname[20]; char password[20]; char mes[1024];

int thr_id; /* thread ID for the newly created thread */

pthread_t p_thread; /* thread's structure */

if(argc!=1) { }

if((host=gethostbyname(strhost))==NULL) { }

/* 客户程序开始建立 sockfd 描述符 */ printf(\正在建立套接口...\\n\

if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) { }

/* 客户程序填充服务端的资料 */ bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons(PORT);

server_addr.sin_addr=*((struct in_addr *)host->h_addr); printf(\套接口创建成功,正在链接服务器...\\n\/* 客户程序发起连接请求 */

if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1) { }

/* 连接成功了 */

printf(\链接服务器成功\\n欢迎来到聊天室!\\n\printf(\请输入你的用户昵称:\\n\scanf(\printf(\请输入登录密码:\\n\scanf(\

fprintf(stderr,\exit(1);

fprintf(stderr,\exit(1);

fprintf(stderr,\exit(1);

fprintf(stderr,\exit(1);

printf(\登陆成功\

// write(sockfd,clientname,sizeof(clientname)); }

(2)服务器代码 #include #include #include #include #include #include #include

thr_id = pthread_create(&p_thread, NULL, recvfromserver, NULL); while(1) { }

/* 结束通讯 */ close(sockfd); exit(0);

memset(buffer,0,sizeof(buffer)); memset(mes,0,sizeof(mes)); scanf(\ strcat(mes,clientname); strcat(mes,\strcat(mes,buffer);

if((write(sockfd,mes,sizeof(mes)))==-1) { }

if(strcmp(buffer,\{ }

break;

fprintf(stderr,\exit(1);

printf(\开始聊天@(\\\断开连接)\\n\\n\

// printf(\


Linux课程设计(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:二年级地方课教学计划

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: