//java socket client example
import java.io.*;
import java.net.*;
public class socket_client {
public static void main(String[] args) throws IOException {
Socket s = new Socket();
String host = "1.1.1.1";
PrintWriter s_out = null;
BufferedReader s_in = null;
try {
s.connect(new InetSocketAddress(host, 12656));
System.out.println("Connected");
// writer for socket
s_out = new PrintWriter(s.getOutputStream(), true);
// reader for socket
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
// Host not found
catch (UnknownHostException e) {
System.err.println("Don't know about host : " + host);
System.exit(1);
}
// Send message to server
String message = "this is the msg";
s_out.println(message);
System.out.println("Message send");
// Get response from server
String response;
while ((response = s_in.readLine()) != null) {
System.out.println(response);
}
// close the socket
s.close();
// close the i/o streams
s_out.close();
s_in.close();
}
}
答案 0 :(得分:1)
套接字被阻止,因为服务器端没有处理意外的套接字关闭。你有两个选择 - 或者更确切地说,两个步骤,如果你想要彻底 - 解决这个问题。
这是优雅处理意外终止的server socket code from O'Reilly示例:
try {
ServerSocket server = new ServerSocket(5776);
while (true) {
Socket connection = server.accept( );
try {
OutputStreamWriter out
= new OutputStreamWriter(connection.getOutputStream( ));
out.write("You've connected to this server. Bye-bye now.\r\n");
connection.close( );
}
catch (IOException e) {
// This tends to be a transitory error for this one connection;
// e.g. the client broke the connection early. Consequently,
// we don't want to break the loop or print an error message.
// However, you might choose to log this exception in an error log.
}
finally {
// Most servers will want to guarantee that sockets are closed
// when complete.
try {
if (connection != null) connection.close( );
}
catch (IOException e) {}
}
}
catch (IOException e) {
System.err.println(e);
}
答案 1 :(得分:1)
Telnet中没有断开子协议。您所要做的就是关闭插座。
如果我没有正确断开连接,我从未见过或听说过Telnet服务器“阻塞端口”。我有一个生产Telnet客户端,只做那个,并且已经正常工作了五六年。并且任何不能正常处理意外断开连接的服务器都存在严重错误。
问题出在其他地方,可能在(未指定的)服务器本身。要按照您的描述行事,它必须完全忽略流条件的结束,并忽略IOExceptions(或者将它们视为对整个过程完全致命)。它也必须是单线程的。我发现很难相信这种服务器的存在,或者确实存在这个问题。
请注意,您只需关闭's_out',这是您在套接字输出流中包裹的最外层的流/写入器。如果必须关闭输入流和套接字,请在关闭输出流/写入器后执行此操作。