#java #c #sockets #hp-nonstop #tandem
#java #c #сокеты #hp-непрерывное #тандем
Вопрос:
Я новичок в программировании сокетов и пытаюсь реализовать клиент-сервер с использованием TCP. Клиент написан на Java в Windows, а сервер написан на C в тандеме / Hp-NonStop. Я могу подключиться и отправить запрос на сервер.
Но я не могу отправить ответ клиенту с сервера, пока он запущен. Только когда я останавливаю сервер, он отправляет ответ клиенту.
Любой пример, объяснение или ссылки были бы оценены.
Сервер работает в режиме ожидаемого ввода-вывода. Ниже приведен мой серверный код:
while (1) {
/* Accept a connection on this socket. The accept call places the
client's address in the sockaddr_in structure named clientaddr.*/
clientaddrlen = sizeof(clientaddr);
if( accept_nw(s, (struct sockaddr *)amp;clientaddr, amp;clientaddrlen, tag) <0) {
perror("accept");
exit(3);
}
if( fe = IOCheck(acceptWait) ) { /* initially, wait -1; maybe change afterwards? */
if( fe == 40 ) {
printf( "Timed out after %ld secs wtg Client connect. Terminating.n",acceptWait/100 );
FILE_CLOSE_((short)s);
exit(0);
} else {
printf( "AWAITIO error %d from accept_nwn",fe );
exit(3);
}
}
/* Need a new socket for the data transfer
Resembles the earlier call */
if ((new_s = socket_nw(AF_INET, SOCK_STREAM,0,2,0)) < 0) {
perror ("Socket 2 create failed.");
exit (4);
}
/* Make the connection */
if ( accept_nw2(new_s, (struct sockaddr *)amp;clientaddr, tag2) < 0) {
perror ("2nd Accept failed.");
exit (5);
}
if( fe = IOCheck(-1) ) {
printf( "AWAITIO error %d, tag %ld from 2nd
accept_nwn",fe,tagBack );
exit(4);
}
/* Receive data from the client.
recv_nw() - awaitio() should be in a loop until a logical record
has been received. In this example, we expect the short messages
to be completed in a single recv_nw() */
if( recv_nw(new_s, databuf, sizeof(databuf), 0, tag2) < 0 ) {
if( errno == ESHUTDOWN || errno == ETIMEDOUT || errno == ECONNRESET ) {
FILE_CLOSE_((short)new_s);
continue;
} else {
perror( "recv_nw error" );
exit( 6 );
}
}
if( fe = IOCheck(timeout) ) {
if( fe == 40 ) { /* abandon and start over */
FILE_CLOSE_((short)new_s);
continue;
} else {
printf( "AWAITIO error %d from recv_nwn",fe );
exit(6);
}
}
databuf[dcount] = ''; /* dcount set by IOCheck */
/* Retrieve the client name using the address in the sockaddr_in
structure named clientaddr. A call to gethostbyaddr expects an
IPv4 address as input. */
hp = gethostbyaddr((char *)amp;clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
/* Convert the client's 32-bit IPv4 address to a dot-formatted
Internet address text string. A call to inet_ntoa expects an
IPv4 address as input. */
ap = inet_ntoa(clientaddr.sin_addr);
port = ntohs(clientaddr.sin_port);
printf("Request received from");
if (hp != NULL) printf(" %s", hp->h_name);
if (ap != NULL) printf(" (%s)", ap);
printf(" port %dn"%s"n", port, databuf);
/* Send a response to the client. */
if (send_nw2(new_s, response, (int)strlen(response), 0, tag2) < 0) {
perror("send_nw2");
FILE_CLOSE_((short)new_s);
continue;
}
if( fe = IOCheck( -1 ) ) {
FILE_CLOSE_((short)new_s);
continue;
}
} /* while */
Ниже приведен мой клиентский код для отправки и получения запроса и ответа.
private String writeToAndReadFromSocket(Socket socket, String writeTo) throws Exception
{
try
{
// write text to the socket
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(writeTo);
bufferedWriter.flush();
// read text from the socket
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String str;
while ((str = bufferedReader.readLine()) != null)
{
sb.append(str "n");
}
// close the reader, and return the results as a String
bufferedReader.close();
return sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
throw e;
}
}
Ответ №1:
Ваш серверный код абсолютно неверен. Действительно ли он принимает без ошибок? Вам не нужно создавать второй сокет, и вы должны вызвать accept для первого сокета.
Комментарии:
1. Серверный код представляет собой пример программы, предоставленной Hp в их руководстве по программированию NonStop TCP / IP. Да, соединение принято без ошибок. В первый раз я вызываю accept в первом сокете. Даже если я не создаю второй сокет, я сталкиваюсь с той же проблемой, т. е. сервер не отправляет ответ обратно во время его выполнения, только когда сервер остановлен или сокет закрыт, сервер отправляет ответ.
2. Странности. В отличие от любого другого TCP API, который я когда-либо видел за почти 30 лет. Вы читаете строки, но вы не пишете строки.
Ответ №2:
Попробуйте отправить запрос с помощью утилиты telnet, возможно, используемый вами клиент буферизует данные, из-за чего может показаться, что сервер не отвечает..