- 论坛徽章:
- 0
|
现在有一段比较恶搞和无聊的程序,纯属是新手练手,虽然程序的功能没有什么意义,但是有个问题,需要大家指点。请大家看看:- /*
- * psc.c
- *
- * Created on: 2010-10-19
- * Author: hacker
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <stdlib.h>
- void client();
- int main()
- {
- int server_sockfd, client_sockfd;//保存服务器和客户端套接字标识
- int server_len, client_socklen;//保存服务器和客户端消息长度
- struct sockaddr_in server_address;//定义服务器套接字地址
- struct sockaddr_in client_address;//定义客户端套接字地址
- server_sockfd = socket(AF_INET, SOCK_STREAM, 0);//定义套接字类型
- server_address.sin_family = AF_INET;//定义套接字地址中的域
- server_address.sin_addr.s_addr = inet_addr("127.0.0.1");//定义套接字地址
- server_address.sin_port = 9734;//定义套接字端口
- server_len = sizeof(server_address);
- bind(server_sockfd, (struct sockaddr*) &server_address,server_len);
- //定义套接字名字
- listen(server_sockfd,5);//创建套接字列队
- while(1){
- char ch;
- printf("服务器等待消息...\n");
- client_socklen = sizeof(client_address);
- client_sockfd = accept(server_sockfd, //接收连接
- (struct sockaddr*)&client_address,
- (socklen_t *__restrict) &client_socklen);
- read(client_sockfd,&ch,1);//读取客户端连接
- ch++;
- write(client_sockfd,&ch,1);//向客户端传送消息
- close(client_sockfd);
- }
- while(1){
- pthread_t client_p;
- void * thread_result;
- pthread_create(&client_p, NULL, (void*)client, NULL);
- if(client_p != 0)
- {
- perror("线程创建失败");
- exit(EXIT_FAILURE);
- }
- pthread_join(client_p,&thread_result);
- }
- return 0;
- }
- void client()
- {
- int sockfd;
- int len;
- struct sockaddr_in address;
- int result;
- char ch = 'A';
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = inet_addr("127.0.0.1");
- address.sin_port = 9734;
- len = sizeof(address);
- result = connect(sockfd,(struct sockaddr*) &address,len);
- if(result == -1){
- perror("连接失败");
- return 1;
- }
- write(sockfd, &ch, 1);
- read(sockfd, &ch, 1);
- printf("来自服务器的消息是%c\n",ch);
- close(sockfd);
- }
复制代码 现在的问题是,主线程是一个死循环,但是主线程(server)必须先开启,然后开启另一个线程(client)。怎么才能实现呢? |
|