我编写了以下客户端,该客户端仅连接到本地主机,即连接机器的IP,而不是连接到不同计算机上不同IP的服务器。 我连接到外面时遇到的错误是Connection拒绝 如何让它连接到本地主机外?
我的代码如下
public ChatClient(JTextField address, JTextField port, JTextField user,
JTextField text, JTextArea tapane3, JTextArea tapane4) {
// TODO Auto-generated constructor stub
this.address=address;
this.user=user;
this.text=text;
this.port=port;
add=address.getText();
textarea=tapane3;
showusers=tapane4;
}
public void sendToPort(String str) throws IOException {
Socket socket = null;
//String str = "Hello World";
try {
out.write(str, 0, str.length());
out.flush();
} catch (IOException e) {
System.err.print(e);
} finally {
}
}
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Send"))
{
try {
textarea.append(SendMessage()+"\n");
System.out.println(SendMessage());
sendToPort("x");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Connect"))
{
try {
String prt=port.getText();
cs = new Socket(add, Integer.parseInt(prt));
out =new OutputStreamWriter(cs.getOutputStream(), "UTF-8");
showusers.setText(user.getText());
//sendToPort(Integer.parseInt(prt), Address);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Disconnect"))
{
try {
cs.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void Connect() throws NumberFormatException, UnknownHostException, IOException {
// TODO Auto-generated method stub
}
public String SendMessage() {
// TODO Auto-generated method stub
{
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String getdate=(dateFormat.format(date));
String content = text.getText();
String from = String.format(user.getText());
String all = "START:" + getdate + ":" + from + ":"+"MESSAGE:" + content + ":END";
//textarea.setText(all);
try {
out.write(all);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return all;
}
答案 0 :(得分:-1)
此外,您需要移植您的端口。 你可以在这里阅读和学习如何做: http://portforward.com/