这个问题是对此问题的后续问题: BufferedReader readLine method hangs and block program
我现在有一台服务器和一台运行顺畅的客户端,但后来我尝试使用swing实现GUI界面。使用相同的代码,套接字构造函数失败。
我的班级是这样的:
public class TCPClient {
public BufferedWriter ostream = null;
public BufferedReader istream = null;
public TCPClient(String host, String port) throws UnknownHostException {
InetAddress ip = InetAddress.getByName(host);
try {
Socket socket = new Socket(host, Integer.parseInt(port));
ostream = new BufferedWriter(socket.getOutputStream());
istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
从主函数调用时,此代码非常有效。在摇摆中,我有一个按钮,调用以下方法:
private void enviarMsgTCP() throws IOException {
screenOutput.append("Sent:\n" + mensagem.getText() + "\n");
if (client == null){
try {
client = new TCPClient(destIp.getText(), port.getText());
} catch (UnknownHostException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
saidaTexto.append("Não foi possível se conectar ao host.\n");
}
}
使用此代码,下面的行(在TCPClient中)引发异常:
Socket socket = new Socket(host, Integer.parseInt(port));
异常堆栈跟踪:
21/10/2011 21:44:42 cliente.ClienteTCP <init>
GRAVE: null
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
它能是什么? 再次
答案 0 :(得分:2)
拒绝连接意味着没有任何内容正在侦听连接时指定的IP:端口。
为什么还有DataOutputStream?