【发布时间】:2015-07-26 00:56:45
【问题描述】:
我编写了以下客户端,它仅连接到本地主机,即连接机器的 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;
}
【问题讨论】:
-
尝试瘦身。您应该只需要几行来连接到服务器并发送一行文本。写a simple program,看看它是否有效。您还应该准确地告诉我们,当您尝试连接到另一台机器时会发生什么,您会遇到什么样的错误。
-
它只是说连接被拒绝,但是当我连接到与本地主机在同一台机器上运行的服务器时,它会连接并发送和接收消息
-
你试过简单的程序吗?您需要一行代码来创建套接字,一行代码来获取 OutputStreamWriter,以及通过它编写一个示例消息。加上样板异常处理和关闭资源。真的很简单,可能会帮助您解决问题。不幸的是,这里没有人可以运行您的代码并找出问题所在...(因为我们没有您的服务器)。
-
那件事,你写了服务器吗?您确定问题出在客户端而不是服务器上吗?
-
我已经编写了服务器并且我的服务器运行良好,它正在连接到本地主机之外的客户端
标签: java sockets client localhost chat