简体   繁体   中英

Java sockets doesn't work on windows

I'm trying to make an program where I'd like to connect two devices in the same wifi, so I'm trying to use sockets.

I have the server code running on my pc and client side on android device. The problem is that the server does not work on windows, but it does on linux. I disconnected all the firewalls, windows and avast, but I still have the same problem. I've tried to use a linux machine as server and windows as client and it works perfectly.

I put some prints to see where it stops and the server side in windows is stop when I try to get the Socket "Socket s = ss.accept();". I don't get any error it just gets stuck there.

I don't know what could be wrong.

Server side

   int port = 2002;  
   try {  
            ServerSocket ss = new ServerSocket(port);

            Socket s = ss.accept();

            InputStream is = s.getInputStream();  
            ObjectInputStream ois = new ObjectInputStream(is); 

            System.out.println((String)ois.readObject());  
            is.close();  
            s.close();  
            ss.close();  
   }catch(Exception e){System.out.println(e);}  

Client side:

try{  
            String hostPortatil = "192.168.1.131";
            String host = "192.168.174.1";
            int port = 2002;
            Socket s = new Socket(hostPortatil, port);  

            OutputStream os = s.getOutputStream();

            ObjectOutputStream oos = new ObjectOutputStream(os);  

            oos.writeObject(new String("another object from the client"));  

            oos.close();  
            os.close();  
            s.close();  
}catch(Exception e){
            System.out.println(e);
}

很可能您尚未将 Windows 防火墙配置为接受端口 2002 上的连接。

Your server is configure to listen connections on port 9999, but client connects using port 2002

Edit:

Start the server on windows and open a cmd.exe:

netstat -an|findstr "2002"

you should see your java process listening for connections. If not then something is wrong. In the linux server open a shell:

telnet 192.168.1.131 2002

You should connect from the linux server to the windows server. Again if not some is wrong.

I think it's because you are running the server side of your program on Windows which will assign the localhost ip to your sever side and that ip is certainly different from the ip of your local Wi-Fi and hotspot connection. I run both client and server side of a sample app on Windows with localhost and worked but didn't worked with ip of my Wi-Fi and hotspot connection on two different platform. I guess it would be fixed by turning the computer to a server!

accept() 方法正在等待客户端建立 TCP 连接,这就是为什么没有输出也没有错误的原因,所以问题似乎出在客户端。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM