我正在编写一个程序,最终制作自己的文件服务器。在服务器运行时,通过在浏览器中键入myIpAddress:port
来在Web浏览器中连接服务器时遇到问题。如果我使用一台计算机同时托管服务器并作为客户端,则此方法有效,但是如果我使用第二台计算机作为客户端,则无效。
我有2个课程,Index
和ClientHandler
public class Index {
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(8080);
DevInterface myFace = new DevInterface(server);
System.out.println("Listening for connection on port 8080");
} catch (IOException e) {
e.printStackTrace();
}
int i = 0;
while(true) {
Socket client = null;
try {
client = server.accept();
ClientHandler clientHandler = new ClientHandler(client);
clientHandler.start();
System.out.println("got a client");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这是将我的html发送到服务器的ClientHandler类。
public class ClientHandler extends Thread{
private Socket client = null;
private PrintWriter out = null;
ArrayList<Socket> clientList = null;
public ClientHandler(Socket client) {
this.client = client;
}
public ClientHandler(Socket client, ArrayList<Socket> clientList) {
this.client = client;
this.clientList = clientList;
}
public void run() {
try {
out = new PrintWriter(client.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("\r\n");
out.println("<p>Hello World</p>");
out.flush();
out.close();
if(client!=null) {client.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}