[问题] TCP/IP server 问题 ~~

楼主: wowhorng (筑梦踏实)   2015-12-09 22:53:23
各位高手们 ~ 请问一下
要在 Linux 建立 TCP server,程式如下 ...
遇到的问题:
(1) 为什么断线之后,重新连线却连不上?
(2) port 被占住(client 端不正常断线),应该如何解决被占住的问题?
(3) 假如要支援多人登入,请问要如何修改或是哪里可以找到相关资料?
(4) 请问 time out 的话,要怎么解决,让 server 可以自动重新运作?
Thanks
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/errno.h>
#define SERV_PORT 5134
#define MAXNAME 1024
extern int errno;
main()
{
int socket_fd; /* file description into transport */
int recfd; /* file descriptor to accept */
int length; /* length of address structure */
int nbytes; /* the number of read **/
char buf[BUFSIZ];
struct sockaddr_in myaddr; /* address of this service */
struct sockaddr_in client_addr; /* address of client */
if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) <0) {
perror ("socket failed");
exit(1);
}
bzero ((char *)&myaddr, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(SERV_PORT);
if (bind(socket_fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) <0) {
perror ("bind failed");
exit(1);
}
if (listen(socket_fd, 20) <0) {
perror ("listen failed");
exit(1);
}
length = sizeof(client_addr);
printf("Server is ready to receive !!\n");
printf("Can strike Cntrl-c to stop Server >>\n");
while (1) {
if ((recfd = accept(socket_fd,
(struct sockaddr_in *)&client_addr, &length)) <0) {
perror ("could not accept call");
exit(1);
}
if ((nbytes = read(recfd, &buf, BUFSIZ)) < 0) {
perror("read of data error nbytes !");
exit (1);
}
printf("Create socket #%d form %s : %d\n", recfd,
inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port));
printf("%s\n", &buf);
/* return to client */
if (write(recfd, &buf, nbytes) == -1) {
perror ("write to client error");
exit(1);
}
close(recfd);
printf("Can Strike Crtl-c to stop Server >>\n");
}
}
作者: soso7885 (YOHO)   2015-12-10 18:26:00
setsockopt
作者: Qbsuran (Qbsuran)   2015-12-10 18:44:00
SO_REUSEADDR

Links booklink

Contact Us: admin [ a t ] ucptt.com