2)发送功能
(
3. 服务器端功能模块(Server)
服务器端,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。
3.代码实现
(1)客户端代码
#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
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(\