JAVA中两台电脑通信,使用TCP / IP在两台不同的计算机之间进行通信

本文探讨了如何使两个Java程序在不同计算机上通过Socket进行通信。通常示例中使用127.0.0.1或localhost进行本地通信。要实现跨网络通信,两台计算机需要在同一局域网内或彼此的IP地址需可互联网访问。通过Windows的cmd或Linux终端获取本地IP地址。如果不在同一局域网,可能需要考虑路由器的防火墙政策。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've been studying how to use sockets to make two java programs communicate.

Now, on each example I've gone through, they've always placed the "server side program" on the same computer on which the "client side program" was, and of course the IP set was either 127.0.0.1 , or simply "localhost".

Now, my question is:

how do I get to communicate the two programs if one is on a computer, and one on another?

I've tried to set the IP as the one my computer has when connected to internet (the one I found simply by googling "what's my IP"), but that way it doesn't seems to work.

Can anyone explain me better how I can make it work?

解决方案

The computers will need to be on the same network or their IP address will need to be accessible to the internet. If you are in windows, you can find the local IP address by opening a cmd window (press windows key + R then type cmd) and running ipconfig. On linux (maybe it works on Mac as well) you can run ifconfig in a terminal. If your computers are on the same local area network you should be able to use the IP addresses indicated by those commands.

If they are not on the same local area network, a router in between the computers may have a firewall policy which is blocking the connection.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值