我的聊天客户端只连接到本地主机
问题描述:
我编写了以下客户端,它仅连接到本地主机,即连接到本机的ip,但不连接到在不同计算机上的不同ip上运行的服务器。 我连接到外部时遇到的错误是连接被拒绝 如何使其连接到本地主机之外?我的聊天客户端只连接到本地主机
我的代码如下
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;
}
答
首先,你需要使用本机的计算机的公网IP,而不是你的本地主机。 https://www.whatismyip.com/
此外,您需要端口转发您的端口。 你可以阅读和学习如何在这里: http://portforward.com/
尝试减肥。您应该只需要一些线路连接到服务器并发送一行文本。编写一个简单的程序(http://stackoverflow.com/help/mcve),看看它是否有效。您还应该告诉我们,当您尝试连接到不同的机器时会发生什么情况,您会得到什么样的错误。 – dcsohl
它只是说连接被拒绝,但是当我连接到与本地主机在同一台机器上运行的服务器时,它会连接并发送和接收消息 – Splasher
您是否试过简单的程序?您需要一行代码来创建套接字,一个获取OutputStreamWriter,一个通过它写入示例消息。 Plus样板异常处理和关闭资源。真的很简单,可能会帮助你解决问题。不幸的是,这里没有人可以运行你的代码并找出有什么问题......(因为我们没有你的服务器)。 – dcsohl