8
回答
java 局域网socket连接不到服务器
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

    我的服务器是centos,两个java文件MyServer和MyClient。在本机上可以相互连接,但是把MyServer运行在centos之后socket就通信不了了。

MyServer.java

public class MyServer {

	public static void main(String[] args) throws IOException{
		ServerSocket server=new ServerSocket(2000);
		while(true){
			Socket socket=server.accept();
			System.out.println("yes");
			new MySocketThread(socket).start();
		}
		
		
	}
	
}
class MySocketThread extends Thread{
	private Socket socket;
	public MySocketThread(){}
	public MySocketThread(Socket socket) {
		this.socket=socket;
	}
	
	@Override
	public void run() {
		try {
			handle(socket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handle(Socket socket) throws IOException{
		
		BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter out=new PrintWriter(socket.getOutputStream());
		
		while(true){
			String msg=in.readLine();
			System.out.println(msg);
			
			out.println(msg);
			out.flush();
			
			if(msg.equals("bye")){
				break;
			}
		}
	}
}
MyClient.java

public class MyClient {

	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub
		
		System.out.println("start");
		Socket socket=new Socket("192.168.10.3",2000);
		System.out.println("start");
		BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter out=new PrintWriter(socket.getOutputStream());
		BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
		
		System.out.println("start");
		System.out.println(socket.getInetAddress());
		while(true){
			String msg=read.readLine();
			out.println(msg);
			out.flush();
			if(msg.equals("bye")){
				break;
			}
			System.out.println(in.readLine());
		}
	}

}
192.168.10.3为服务器的ip,在本机中把它换成localhost测试没有问题。

运行结果就是客户端和服务器链接不上。

举报
Callen
发帖于4年前 8回/2K+阅

以下是问题补充:

  • @Callen :我一经关了防火墙: chkconfig iptables off (4年前)
顶部