我正在使用套接字创建一个简单的java聊天框。当我在同一台计算机上运行许多客户端时,一切都很好,但是当我在不同的PC上试用它们时,它们并不共享这些信息。我怎么能解决这个问题?我想这与端口和主机有关,但不确定。我的连接方法如下。
public static void Connect() {
try {
final int port = 444;
String hostname = "";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
final String host = "Laurie-PC";
Socket sock = new Socket(host, port);
System.out.println("You connected to " + host);
ChatClient = new A_Chat_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(UserName);
out.flush();
Thread X = new Thread(ChatClient);
X.start();
} catch (Exception E) {
System.out.println(E);
JOptionPane.showMessageDialog(null, "Server not responding");
System.exit(0);
}
}
答案 0 :(得分:0)
这是服务器代码
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class A_Chat_Server {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
try {
final int port = 444;
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for clients...");
A_Chat_Client_GUI.main(args);
while (true) {
Socket sock = server.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
AddUserName(sock);
A_Chat_Server_Return chat = new A_Chat_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch (Exception X) {
System.out.println(X);
}
}
public static void AddUserName(Socket X) throws IOException {
Scanner input = new Scanner(X.getInputStream());
String UserName = input.nextLine();
CurrentUsers.add(UserName);
for (int i = 0; i < A_Chat_Server.ConnectionArray.size(); i++) {
Socket temp_sock = A_Chat_Server.ConnectionArray.get(i);
PrintWriter out = new PrintWriter(temp_sock.getOutputStream());
out.println("????1!!!!!!???######@22" + CurrentUsers);
out.flush();
}
}
}