将socket服务器端程序放入多线程后接收不到数据?
写了一个服务器端/客户端的socket程序。在本机上测试,运行正常。有一个不明白的地方:我客户端连接的地址是127.0.0.1,但是服务器端读出来的时候,第一次不是127.0.0.1,。具体可见下面的输出信息:
服务器端代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#define MAX_LINE 200
void my_fun(char * p)
{
if(p == NULL)
return;
for (; *p != '\0'; p++)
if(*p >= 'A' && *p <= 'Z')
*p = *p -'A'+ 'a';
}
int main(void)
{
struct sockaddr_in sin;
struct sockaddr_in cin;
int l_fd;
int c_fd;
socklen_t len;
char buf;
char savebuf;
char addr_p;
int port = 8000;
int n;
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
l_fd = socket(AF_INET, SOCK_STREAM, 0);
bind(l_fd, (struct sockaddr *)&sin, sizeof(sin));
listen(l_fd, 10);
printf("waiting ...\n");
while(1)
{
c_fd = accept(l_fd, (struct sockaddr *) &cin, &len);
n = read(c_fd, buf, MAX_LINE);
inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p));
printf("client IP is %s, port is %d\n", addr_p, ntohs(sin.sin_port));
printf("buf:%s \n",buf);
my_fun(buf);
write(c_fd, buf, n);
close(c_fd);
}
if(close(l_fd) == -1){
perror("fail to close");
exit(1);
}
return 0;
}
客户端代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#define MAX_LINE 200
int main(int argc, char *argv[])
{
struct sockaddr_in sin;
char buf;
int sfd;
int port = 8000;
char *str = "TEST STRING";
if (argc > 1)
str = argv;
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr);
sin.sin_port = htons(port);
sfd = socket(AF_INET, SOCK_STREAM, 0);
connect(sfd, (struct sockaddr_in *)&sin, sizeof(sin));
write(sfd, str, strlen(str) + 1);
read(sfd, buf, MAX_LINE);
printf("recive from server: %s\n", buf);
close(sfd);
return 0;
}
程序输入输出信息:input:
# ./client "wwwwwwww"
recive from server: wwwwwwww
# ./client "wwwwwwww"
recive from server: wwwwwwww
# ./client "wwwwwwww"
recive from server: wwwwwwww
# ./client "wwwwwwww"
recive from server: wwwwwwww
output:
# ./server
waiting ...
client IP is 56.249.234.191, port is 8000 //为什么这里得到的IP不是127.0.0.1
buf:wwwwwwww
client IP is 127.0.0.1, port is 8000
buf:wwwwwwww
client IP is 127.0.0.1, port is 8000
buf:wwwwwwww
client IP is 127.0.0.1, port is 8000
buf:wwwwwwww 然后我将服务器端的代码放入一个多线程中,
main函数的代码为:
int main(int argc, char *argv[])
{
pthread_t t;
pthread_create(&t,NULL,mysocket,NULL); //socket
while(1)
{
}
return 0;
}
多线程函数mysocket与上面服务器端代码一样。
运行后只能得到:
client IP is 56.249.234.191, port is 8000
IP地址还会不一样。没有接收到客服端发送的数据。
请大家帮我分析一下,问题可能出在上面地方?
如果以后不是在本机运行,是不是只要将服务器的IP知道告知客户端,让客户端去连接这个IP就可以?
端口是服务器端指定的,还是客服端自己定就可以了?
初学者,往指导。 len你没有赋值, 这是一个in/out参数, 你需要len = sizeof(struct sockaddr_in); 回复 3# linux_c_py_php
眼神真犀利 是的。
这是我在拷贝代码的时候犯的错。实际的程序是有这一句的。谢谢。
没人知道啊。 问题解决了
自己2了
把多线程里面的输出语句注释掉了。。。。:'(:'(:'(
上面的代码调试通过
页:
[1]