[問題] 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