简体   繁体   English

Java套接字编程

[英]socket programming in Java

I want to run a client/server application that is built in Java using socket connection. 我想运行使用套接字连接以Java内置的客户端/服务器应用程序。 If I run both the server and the client program in same machine, the client and server communicate each other as expected. 如果我在同一台计算机上同时运行服务器和客户端程序,则客户端和服务器将按预期相互通信。 But on the other hand, if run the client program on some other system, I get an exception 但是另一方面,如果在其他系统上运行客户端程序,则会出现异常

java.net.ConnectException: Connection timed out: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:519)
        at java.net.Socket.connect(Socket.java:469)
        at java.net.Socket.<init>(Socket.java:366)
        at java.net.Socket.<init>(Socket.java:180)

Could anyone help me solve this problem? 谁能帮我解决这个问题?

In addition to what Bhushan said, check that it isn't being blocked by a firewall. 除了Bhushan所说的以外,请检查它是否未被防火墙阻止。 In particular, Windows XP's built in firewall often catches me out. 特别是Windows XP的内置防火墙经常使我失望。

You can also test your TCP connection (I'm assuming you're using TCP) by telnet'n from the client to the server, ie 您也可以通过telnet'n从客户端到服务器来测试TCP连接(假设您正在使用TCP),即

client.host] telnet ip.of.server port.of.application 客户端主机] telnet ip.of.server.port.of.application

and see what response you get. 看看你得到什么回应。 If you get anything other than a timeout, then you're using the wrong address/port values in your Socket object. 如果除了超时以外,您还没有在Socket对象中使用错误的地址/端口值。

How you created the Socket object in client? 您如何在客户端中创建Socket对象? Can we see the code of server and client both? 我们可以同时看到服务器和客户端的代码吗? May be you are using localhost while creating the client Socket object. 可能是您在创建客户端Socket对象时正在使用localhost。 Instead of localhost use the ip address or the hostname of the machine which is running the Server. 代替本地主机,使用运行服务器的计算机的IP地址或主机名。 Also check if both the machines are on same network and can see each other. 此外,还要检查两台计算机是否在同一网络上并且可以互相看见。

the main problem what i think is that you have to open the port. 我认为的主要问题是您必须打开端口。 The server and clients are communicating using the same port. 服务器和客户端使用同一端口进行通信。 when ur using the same machine in that case all the ports are open for it self. 当您使用同一台机器时,所有端口均会自行打开。 but to connect with separate systems u have to open the port. 但是要连接单独的系统,您必须打开端口。 actually this is the job of the administrator to open the port. 实际上,这是管理员打开端口的工作。

Thanks Sunil Kumar Sahoo 感谢Sunil Kumar Sahoo

听起来您的服务器上有防火墙(Windows和Linux默认情况下启用了防火墙),并且您需要允许其他计算机在您使用的端口上进行连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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