Java基础学习

Java网络实例

2019-07-28  本文已影响1人  JWking

1、Java 实例 – 获取指定主机的IP地址:使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址。

public class Net_GetIP {

public Net_GetIP() {

InetAddress address =null;

try {

address = InetAddress.getByName("www.baidu.com");

}

catch (UnknownHostException e) {

System.exit(2);

}

System.out.println(address.getHostName() +"的IP地址wei:" + address.getHostAddress());

System.exit(0);

}

}

执行结果:

2、Java 实例 – 查看端口是否已使用:

public class Net_PortCheck {

public static void main(String[] args) {

Socket Skt;

String host ="localhost";

if (args.length >0) {

host = args[0];

}

for (int i =0; i <6; i++) {

try {

System.out.println("查看 "+ i +"未使用");

Skt =new Socket(host, i);

System.out.println("端口 " + i +" 已被使用");

}

catch (UnknownHostException e) {

System.out.println("Exception occured"+ e);

break;

}

catch (IOException e) {

}

}

}

}

执行结果:

3、Java 实例 – 获取本机ip地址及主机名:使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名。

public class Net_GetLocal {

public Net_GetLocal()throws Exception {

InetAddress addr = InetAddress.getLocalHost();

System.out.println("Local HostAddress: "+addr.getHostAddress());

String hostname = addr.getHostName();

System.out.println("Local host name: "+hostname);

}

}

执行结果:

4、Java 实例 – 获取远程文件大小:

public class Net_GetFileSize {

public Net_GetFileSize()throws Exception {

int size;

URL url =new URL("http://photocdn.sohu.com/20111207/Img328215620.jpg");

URLConnection conn = url.openConnection();

size = conn.getContentLength();

if (size <0)

System.out.println("无法获取文件大小。");

else

            System.out.println("文件大小为:" + size +" bytes");

conn.getInputStream().close();

}

}

执行结果:

5、Java 实例 – Socket 实现多线程服务器程序:使用 Socket 类的 accept() 方法和 ServerSocket 类的 MultiThreadServer(socketname) 方法来实现多线程服务器程序。

public class Net_MultiThreadServerextends Thread{

Socketcsocket;

Net_MultiThreadServer(Socket csocket) {

this.csocket = csocket;

}

public static void main(String args[])

throws Exception {

ServerSocket ssock =new ServerSocket(1234);

System.out.println("Listening");

while (true) {

Socket sock = ssock.accept();

System.out.println("Connected");

new Thread(new Net_MultiThreadServer(sock)).start();

}

}

public void run() {

try {

PrintStream pstream =new PrintStream

(csocket.getOutputStream());

for (int i =100; i >=0; i--) {

pstream.println(i +

" bottles of beer on the wall");

}

pstream.close();

csocket.close();

}

catch (IOException e) {

System.out.println(e);

}

}

}

执行结果:

6、Java 实例 – 查看主机指定文件的最后修改时间:

public class Net_FileTime {

public Net_FileTime()throws Exception {

URL u =new URL("http://127.0.0.1/test/test.html");

URLConnection uc = u.openConnection();

SimpleDateFormat ft =new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");

uc.setUseCaches(false);

long timestamp = uc.getLastModified();

System.out.println("test.html 文件最后修改时间 :" + ft.format(new Date(timestamp)));

}

}

执行结果:

7、Java 实例 – 使用 Socket 连接到指定主机:使用 net.Socket 类的 getInetAddress() 方法来连接到指定主机。

public class Net_Ping {

public static void main(String[] args) {

try {

InetAddress addr;

Socket sock =new Socket("www.baidu.com",80);

addr = sock.getInetAddress();

System.out.println("连接到 " + addr);

sock.close();

}catch (java.io.IOException e) {

System.out.println("无法连接 " + args[0]);

System.out.println(e);

}

}

}

执行结果:

8、Java 实例 – 网页抓取:使用 net.URL 类的 URL() 构造函数来抓取网页。

public class Net_GetWeb {

public Net_GetWeb()throws Exception {

URL url =new URL("http://www.baidu.com");

BufferedReader reader =new BufferedReader

(new InputStreamReader(url.openStream()));

BufferedWriter writer =new BufferedWriter

(new FileWriter("data.html"));

String line;

while ((line = reader.readLine()) !=null) {

System.out.println(line);

writer.write(line);

writer.newLine();

}

reader.close();

writer.close();

}

}

执行结果:

9、Java 实例 – 获取 URL响应头的日期信息:使用 HttpURLConnection 的 httpCon.getDate() 方法来获取 URL响应头的日期信息。

public class Net_URLGetDate {

public Net_URLGetDate()throws Exception {

URL url =new URL("http://www.runoob.com");

HttpURLConnection httpCon =

(HttpURLConnection) url.openConnection();

long date = httpCon.getDate();

if (date ==0)

System.out.println("无法获取信息。");

else

            System.out.println("Date: " +new Date(date));

}

}

执行结果:

10、Java 实例 – 获取 URL 响应头信息:

public class Net_URLCon {

public Net_URLCon()throws IOException {

URL url =new URL("http://www.baidu.com");

URLConnection conn = url.openConnection();

Map headers = conn.getHeaderFields();

Set keys = headers.keySet();

for( String key : keys ){

String val = conn.getHeaderField(key);

System.out.println(key+"    "+val);

}

System.out.println( conn.getLastModified() );

}

}

执行结果:

11、Java 实例 – 解析 URL:使用 net.URL 类的 url.getProtocol() ,url.getFile() 等方法来解析 URL 地址。

public class Net_URLAnalyse {

public Net_URLAnalyse()throws Exception {

URL url =new URL("http://www.baidu.com");

System.out.println("URL 是 " + url.toString());

System.out.println("协议是 " + url.getProtocol());

System.out.println("文件名是 " + url.getFile());

System.out.println("主机是 " + url.getHost());

System.out.println("路径是 " + url.getPath());

System.out.println("端口号是 " + url.getPort());

System.out.println("默认端口号是 "

                + url.getDefaultPort());

}

}

执行结果:

12、Java 实例 – ServerSocket 和 Socket 通信实例:

public class Server {

public static void main(String[] args) {

try {

ServerSocket ss =new ServerSocket(8888);

System.out.println("启动服务器....");

Socket s = ss.accept();

System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");

BufferedReader br =new BufferedReader(new InputStreamReader(s.getInputStream()));

//读取客户端发送来的消息

            String mess = br.readLine();

System.out.println("客户端:"+mess);

BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

bw.write(mess+"\n");

bw.flush();

}catch (IOException e) {

e.printStackTrace();

}

}

}

······················································································

public class Client {

public static void main(String[] args) {

try {

Socket s =new Socket("127.0.0.1",8888);

//构建IO

            InputStream is = s.getInputStream();

OutputStream os = s.getOutputStream();

BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(os));

//向服务器端发送一条消息

            bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n");

bw.flush();

//读取服务器返回的消息

            BufferedReader br =new BufferedReader(new InputStreamReader(is));

String mess = br.readLine();

System.out.println("服务器:"+mess);

}catch (UnknownHostException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

}

}

执行结果:

上一篇 下一篇

猜你喜欢

热点阅读