java 如何获取连接网络连接信息

Python09

java 如何获取连接网络连接信息,第1张

importjava.io.IOExceptionimportjava.net.InetAddresspublicclassInetAddressTest{publicstaticvoidmain(String[]args)throwsIOException{InetAddressaddr=InetAddress.getLocalHost()//获取本机ipSystem.out.println("localhost:"+addr)//获取指定服务的一个主机IPaddr=InetAddress.getByName("google.com")System.out.println("google:"+addr)//获取指定服务的所有主机IPInetAddress[]addrs=InetAddress.getAllByName("google.com")for(inti=0i<addrs.lengthi++)System.out.println("google:"+addrs[i]+"number:"+i)//获取远程主机可达性System.out.println(InetAddress.getByName("localhost").isReachable(1000))}}

我想你应该是想问C/S架构中的客户端服务端

两者最常见的方式是通过Socket方式进行通信。

Socket可以理解成一个电线插座的工作过程:

服务器是电源插件, 客户端是电器

C和S通过电线和指定的插孔进行连接,连上后,S将电力源源不断发送到C, C就可以工作了。 当然C也可以反向发送信息到S。 两者可以相互通信。

在建立的过程中代码有一些不同。

在服务端采用API类是ServerSocket

在客户端采用的API是Socket类

连接建立后,双方都通过连接获取输入和输出流从而实现通信。即: InputStream is=socket.getInputStream()

is.read(...)

连接代码:

S端:

ServerSocket server=null

try {

server=new ServerSocket(指定的端口)

}catch(Exception e){

System.out.println("不能监听:"+e.toString())

}

Socket socket=null

try {

socket=server.accept()

InputStream is=socket.getInputStream()

//己通过建立起流,可以读取客户端发来的请求了

//同样也可以发送能过 sokcet.getOutputStream()

.....

}

catch(IOException e){

System.out.println("出错:"+e.toString())

}finally{

try {

if(socket!=null){

socket.close()

server.close()

}

}

catch(IOException e){

e.printStackTrace()

}

}

客户端:

Socket socket=null

try {

socket=new Socket(url,端口)

//获取输出流,从而向服务端发数据

socket.getOutputStream()

//获取输入流,从而可以读服务端的数据

socket.getInputStream()

.....

}catch(Exception e){

e.printStackTrace()

}

finally{

try {

socket.close()

}

catch(IOException e){

e.printStackTrace()

}

}

服务器端:

package net

import java.net.*

import java.io.*

public class TCPServer {

public static void main(String []args) throws Exception{

ServerSocket ss = new ServerSocket(6666)

int count = 0

while (true){

Socket s = ss.accept()

count ++

DataInputStream dis = new DataInputStream(s.getInputStream())

System.out.println("第" + count + "个客户:" + dis.readUTF() + s.getInetAddress() + "port" + s.getPort())

dis.close()

s.close()

}

}

}

客户端:

package net

import java.net.*

import java.io.*

public class TCPClient {

public static void main(String []args) throws Exception{

Socket s = new Socket("127.0.0.1",6666)

OutputStream os = s.getOutputStream()

DataOutputStream dos = new DataOutputStream(os)

dos.writeUTF("HELLO SERVER !")

System.out.println("I am a client !")

dos.flush()

dos.close()

s.close()

}

}