我用C具有應對這種局面使得客戶端程序TCP套接字將數據發送到端口:客戶端使用採用C
1-服務器程序接收端口號8080的客戶端發送UDP數據報端口號X
2-服務器創建使用此TCP套接字端口號X
3-一個新的套接字(TCP),服務器讀出由客戶
(在本地主機上運行的)發送的串
我不需要製作服務器程序,它已經完成了。點1和2被覆蓋,但我已經花了幾天的時間來設法解決第三點問題,但我無法做到這一點> <
我爲客戶端獲得的代碼是這樣的:
#define MYPORT 8080
int main(int argc, char *argv[ ]) {
int sockfd;
/* connector’s address information */
struct sockaddr_in their_addr;
struct hostent *he;
int numbytes;
int sockfd2, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc != 3) {
fprintf(stderr, "Usage: %s <hostname> <message>\n", argv[0]);
exit(1);
}
/* get the host info */
if ((he = gethostbyname(argv[1])) == NULL) {
perror("Error obtaining the client. \n");
exit(1);
}
else printf("Client obtained\n");
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("Error creating UDP socket\n");
exit(1);
}
else printf("UDP Socket done\n");
their_addr.sin_family = AF_INET;
printf("Port: 8080\n");
their_addr.sin_port = htons(MYPORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8);
sockfd2 = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd2 < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
//sending port where the TCP socket will be associated
//server client connects correctly to this port
//and the code it's working fine in this point
if((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1)
{
perror("Client-sendto() error lol!");
exit(1);
}
//port is sent, now let's connect to the port by tcp and write the string
//not working properly from now on
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(atoi(argv[2]));
if (bind(sockfd2,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
listen(sockfd2, 5);
accept(sockfd2, 0, 0);
printf("accepted!\n");
//sending the string to the TCP Port...
if((numbytes = sendto(sockfd2, "hi", 2, 0, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))) == -1)
{
printf("Client-sendto()-TCP error\n");
exit(1);
}
if (close(sockfd) != 0) printf("Client-sockfd-UDP closing is failed!\n");
else printf("Client-sockfd-UDP successfully closed!\n");
if (close(sockfd) != 0) printf("Client-sockfd2-TCP closing is failed!\n");
else printf("Client-sockfd2-TCP successfully closed!\n");
return 0;
}
的代碼適用於前兩個步驟,但在最後一步,現在看來,這不是與TCP端口連接好,因爲我的客戶端程序結束,但我的服務器程序說,他收到空。 當然我總是發送端口> 1024
在此先感謝,任何幫助將如此讚賞。
服務器應該連接回客戶端,對吧?(這是_very_不尋常的。) – Mat
不真正連接回來,服務器通過udp接收端口no X socket,然後它在端口X建立一個tcp連接並從這個新的tcp連接中讀取一個字符串,客戶端被迫發送一個字符串到這個端口(我猜) – LuthorMithos
將客戶端綁定()到TCP端口,然後告訴服務器,它可以拍攝連接回到那個港口;在嘗試連接/讀取時服務器是否返回錯誤?如果是這樣,我猜測沒有實際的連接,因爲沒有人接受該端口上的連接。你似乎已經設法在這裏比賽。 – tbert