服务器端建立的步骤是:
1,建立socket ,用socket()函数。
2,由bind()函数绑定第一步建立的socket(由一个socket描述符代表)。
3,监听,由listen()函数实现。
4, 接收访问由accept()函数实现。
5,创建多线程接收发送的信息,由pthread_create()函数实现。
6,接收消息由recv()函数实现。
7,发送消息由send()函数实现。
下面是今天我写的服务器段代码,
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <pthread.h>
#define MYPORT 3555
#define BACKLOG 10
#define MAXDATASIZE 1024
int sockfd,new_fd;
pthread_t accthread,recthread;
void recmessage(void);
void acceptconnet(void);
void recmessage(void){
while (1) {
int numbetys;
char buf[MAXDATASIZE];
if((numbetys = recv(new_fd, buf, MAXDATASIZE, 0)) == -1){
perror("recv");
exit(1);
}
buf[numbetys] = '\0';
if(strcmp(buf, "exit") == 0){
printf("Client is closed \n");
close(new_fd);
close(sockfd);
exit(1);
}
printf("Client : %s\n",buf);
}
}
void acceptconnet(void){
struct sockaddr_in client_addr;
socklen_t sin_size;
sin_size = sizeof(struct sockaddr_in);
if((new_fd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size)) == -1){
perror("accept");
exit(1);
}
printf("Sever : got connection from %d \n",inet_ntoa(client_addr.sin_addr));
if((pthread_create(&recthread, NULL, (void *)recmessage, NULL)) != 0){
printf("Create thread error !\r\n");
exit(1);
}
}
int main (int argc, const char * argv[])
{
struct sockaddr_in sever_addr;
sever_addr.sin_family = AF_INET;
sever_addr.sin_port = htons(MYPORT);
sever_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(sever_addr.sin_zero), 8);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(1);
}
if(bind(sockfd, (struct sockaddr *)&sever_addr, sizeof(struct sockaddr)) == -1){
perror("bind");
exit(1);
}
if(listen(sockfd, BACKLOG) == -1){
perror("Listen");
exit(1);
}
if(pthread_create(&accthread, NULL, (void *)acceptconnet, NULL) != 0){
printf("Create thread error !\r=n");
exit(1);
}
while (1) {
char msg[MAXDATASIZE];
scanf("%s",msg);
// printf("yourself : %s",msg);
if(send(new_fd, msg, sizeof(msg), 0) == -1){
perror("send");
exit(1);
}
if(strcmp(msg, "exit") == 0){
printf("Bye Bye \n");
close(new_fd);
close(sockfd);
exit(1);
}
}
return 0;
}