【发布时间】:2015-07-08 15:44:08
【问题描述】:
在这个程序中,我尝试从 client_A 向服务器发送 10 条消息(C 0、C 1、D 2 ... C 9)。根据其他用户的建议,我已经编辑了这个问题。现在代码处理了所有可能由系统调用引起的错误,我也修复了很多错误。 我面临的情况是任何系统调用都不会产生错误。程序读取第一条消息,打印它读取的字节数(200),然后显示“没有这样的文件或目录”,并打印它停止的循环数。
这是程序侦听和从套接字读取的代码部分:
//accept connections
tv.tv_sec = 0;
tv.tv_usec = 0;
for (i = 0; i < ns; i++) { //ns=1
len = sizeof(who);
sc[i] = accept (ls, (struct sockaddr *) &who, &len);
if(sc[i] < 0)
perror("Faild to accept socket - in server_process");
n[i] = 1;
}
//select connections and read from sockets
i = 0;
while(i < 10) {
FD_ZERO(&rmask);
for (j = 0; j < ns; j++) {
if (n[j] > 0) {
FD_SET(sc[j], &rmask);
}
}
select (32, &rmask, NULL, NULL, &tv);
for (j = 0; j < ns; j++) {
if ((FD_ISSET(sc[j], &rmask))){
if ((n[j] = read(sc[j], buf, max)) > 0) {
time (&now);
printf ("\n $d bytes read. %s %s", n[j], buf, ctime (&now));
i++;
}else{
perror("Faild to read socket - in server_process");
exit(1);
}
}//if
}//for
}
//close all connections
close(ls);
for (i = 0; i < ns; i++) {
close (sc[i]);
}
这是程序写入套接字的代码部分:
for (i = 0; i < 10; i++) {
x = (rand() % 2);
if (x == 1)
ch = 'C';
else
ch = 'D';
sprintf(msgbuf, "Message from A: %c %d", ch, i);
printf("before wirte to socket!");
wr = write(s, msgbuf, strlen (msgbuf) + 1);
if (wr < 0) {
perror("Faild to write from client_A - in clientA");
}
}
如果需要显示更多代码,请告诉我。它显示的唯一输出是:
字节数:200 消息:来自 A 的消息:C 0 Wed Jul 8 18:29:19 2015
无法读取套接字 - 在 server_process 中:没有这样的文件或目录
2
【问题讨论】:
标签: c sockets client-server