两个内网之间如何通信?

发布时间:2024-05-22 08:53 发布:上海旅游网

问题描述:

两个局域网内如何建立连接,然后聊天或传送文件?用什么方法建立连接:p2p吗?具体怎么用最好有算法Java的,
悬赏100分,诚实守信
能不能有代码,详细些
三楼的答案:两个不同的局域网内的ip都是192.168.1.1——192.168.1.255之间,如何确定外部局域网内的IP是一大问题?

问题解答:

两个局域网站要连接的必须有路由器。必须在三层是通的。不然ping 都ping 不通。无法通信。

而路由器是物理设备。

你所需要的考虑的代码是两台主机之间如何传文件就OK了。
其余的windows 和 路由器代做的。两个局域网如何通查查网络配置就行。不用JAVA管。

关于传文件见下:
//服务器端是创建一个SocketServer接受客户端的请求-----接受文件
//客户端发送一个请求道服务器-----------传送文件的请求

import java.net.*;
import java.io.*;

public class FileServer{

public static void main(String[] a){
String fileName =null;
Socket s =null;
ServerSocket ss =null;
try{
//判断是否在命令行的方式传递了输出文件的文件名
if(a.length<1){
System.out.println("Usage:fileName");
return;
}
else{
ss =new ServerSocket(8001);
fileName =a[0];
}

while(true){
//接受客户端的请求发送文件
s = ss.accept(); //没有请求则阻塞
//以重新启动一个线程的方式,取得客户端发送的文件
new Thread(new Servicer(s,a[0])).start();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
s.close();
} catch(IOException ex){
ex.printStackTrace();
}
}
}
}

class Servicer implements Runnable{
Socket server =null;
String fileName =null;
//传递文件名和Socket
Servicer(Socket s,String fileName){
this.server = s;
this.fileName = fileName;
}
public void run(){
DataInputStream dis =null;
DataOutputStream dos =null;
//创建Socket的输入输出流
try{
InputStream ips =server.getInputStream();
BufferedInputStream br = new BufferedInputStream(ips);
//以DataInputStream来包装字节缓冲输入流
dis = new DataInputStream(br);
//以DataOutputStream来包装字节缓冲输出流
dos = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(fileName)));

byte[] buf = new byte[1024];
//网络传输都是以字节的方式传递的
while((dis.read(buf))!=-1)
{
//一边读,一边写
dos.write(buf,0,buf.length);
}
System.out.println("服务器端传输完毕");
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
dis.close();
dos.close();
}catch(IOException ex){}
}
}
}

class FileClient{
public static void main(String[] args){
DataInputStream dis =null;
DataOutputStream dos =null;
Socket s =null;
try{
//从命令行传递3个参数,分别为服务器IP地址,端口号,要传输的文件名
if(args.length<3){
System.out.println("usage: java TCPClient ServerIP ServerPort FilePath");
return;
}
// Socket s = new Socket(/*InetAddress.getByAddress(*/args[0]),/*)*/Integer.parseInt(args[1]));
else if(args.length==3){
s = new Socket(InetAddress.getByName(args[0]),Integer.parseInt(args[1]));
}
//创建Socket的输入输出流
InputStream ips = s.getInputStream();
OutputStream ops = s.getOutputStream();

dis = new DataInputStream( new BufferedInputStream(
new FileInputStream(args[2])));
dos = new DataOutputStream(new BufferedOutputStream(ops));

byte[] buf = new byte[1024];
while((dis.read(buf))!=-1)
{
dos.write(buf,0,buf.length);
}
System.out.println("客户端传输完毕");

}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
dis.close();
dos.close();
s.close();
}catch(IOException ex){}
}

}

}

技术上讲很复杂,但用软件实现就比较 简单了,如VNN,快递通等。。。

一般是只要设置IP就行 聊天好像没什么局域网聊天的软件

热点新闻