java网络编程

导读:本篇文章讲解 java网络编程,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Java中网络编程离不开java.net包,其中常用的类有

InetAddress  和 SocketImpl
Socket、ServerSocket //TCP编程
DatagramPacket 和 DatagramSocket//UDP编程
URL、URLConnection 和 URLEncoder
  1. 什么是socket: 操作系统中用于网络通信的端点.
    黄色为网卡驱动程序
    在这里插入图片描述

  2. InetAddress:
    封装 IP 地址和 DNS
    示例(运行时记得联网!):

     import java.net.InetAddress;
     import java.net.UnknownHostException;
     public class Test1 {
    
     public static void main(String[] args) {
     	try {
     		InetAddress a1 = InetAddress.getByName("www.sina.com");
     		InetAddress a2 = InetAddress.getByName("127.0.0.1");
     		
     		System.out.println(a1.getHostAddress());
     		System.out.println(a2.getHostName());
     	} catch (UnknownHostException e) {
     		// TODO Auto-generated catch block
     		e.printStackTrace();
     	}
     }
     }
    
  3. ServerSocket
    用来创建套接字(TCP)服务器
    accept( ) 方法用于接收客户端的请求并返回连接到客户端的套接字(Socket),此方法是个阻塞方法

  4. Socket
    用来创建客户端套接字
    构造函数
    Socket(String hostName, int port)
    Socket(InetAddress a, int port)
    常用方法
    InetAddress getInetAddress( )
    int getPort( )//得到远程port
    int getLocalPort( )//得到本地port
    示例(先运行T1在T2):
    T1类:

     import java.io.BufferedReader;
     import java.io.BufferedWriter;
     import java.io.IOException;
     import java.io.InputStreamReader;
     import java.io.OutputStreamWriter;
     import java.net.ServerSocket;
     import java.net.Socket;
     public class T1 {
     	public static void main(String[] args) {
     		ServerSocket ss = null;
     		Socket s = null;
     		BufferedReader reader = null;
     		BufferedWriter writer = null;
     		try {
     			ss = new ServerSocket(10088);	
     			s = ss.accept();
     			reader = new BufferedReader(new InputStreamReader(s.getInputStream()));	
     			String info = null;
     			while(true) {
     				info = reader.readLine();
     				System.out.println(info);
     				if("再见!".equals(info)) {
     					break;
     				}
     			}
     			writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
     			writer.write("你好,!\n");
     			writer.flush();
     			writer.write("欢迎你学习软件开发!\n");
     			writer.flush();
     			writer.write("谢谢!\n");
     			writer.flush();
     			writer.write("再见!\n");
     			writer.flush();	
     			System.out.println(s.getLocalPort());
     			System.out.println(s.getPort());
     		} catch (IOException e) {
     			// TODO Auto-generated catch block
     			e.printStackTrace();
     		}
     	}
     }
    

T2类:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class T2 {
	public static void main(String[] args) {
		Socket s = null;
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			s = new Socket("127.0.0.1", 10088);
			writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
			writer.write("你好\n");
			writer.flush();
			writer.write("我想学习软件开发!\n");
			writer.flush();
			writer.write("谢谢!\n");
			writer.flush();
			writer.write("再见!\n");
			writer.flush();
			reader = new BufferedReader(new InputStreamReader(s.getInputStream()));	
			String info = null;
			while(true) {
				info = reader.readLine();
				System.out.println(info);
				if("再见!".equals(info)) {
					break;
				}
			}	
			System.out.println(s.getLocalPort());
			System.out.println(s.getPort());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  1. 数据报
    单向的,不连续的,不可靠的数据包,其中有2个对象.
    DatagramPacket(相当于邮包) DatagramSocket(相当于邮递员)假设每个人都拥有自己的邮递员
    DatagramSocket
    • 用于发送或接收 DatagramPacket
    • 构造函数
    DatagramSocket()
    DatagramSocket(int port)
    • 常用方法
    void send(DatagramPacket d)
    void receive(DatagramPacket p)
    void close()
    DatagramPacket
    • 用来接收或发送数据,只能存放字节
    • 构造函数
    DatagramPacket(byte[] data, int size) 接收时使用
    DatagramPacket(byte[] data, int size, InetAddress I,
    int port) 发送时使用, InetAddress为远程地
    址,port为远程端口
    • 常用方法
    byte[] getData() 返回数据缓冲区
    int getLength() 返回将要发送或接收到的数据的长度
    示例:
    T1类:(用于收)

     import java.io.IOException;
      import java.net.DatagramPacket;
      import java.net.DatagramSocket;
     import java.net.SocketException;
    
      public class T1 {
    
     public static void main(String[] args) {
     	DatagramSocket socket = null;
     	DatagramPacket packet = null;
     	try {
     		socket = new DatagramSocket(10011);//邮递员通过此端口收进来,相当于收货人地址
     		byte[] pool = new byte[1024];
     		packet = new DatagramPacket(pool, 0, pool.length);
     		socket.receive(packet);
     		String info = new String(packet.getData());
     		System.out.println("T1收到了数据:" + info);
     	} catch (SocketException e) {
     		// TODO Auto-generated catch block
     		e.printStackTrace();
     	} catch (IOException e) {
     		// TODO Auto-generated catch block
     		e.printStackTrace();
     	}	
     	}
      }
    

T2类:(用于发信息)

	import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class T2 {

	public static void main(String[] args) {
		DatagramSocket socket = null;
		DatagramPacket packet = null;
		
		try {
			socket = new DatagramSocket(10022);
			
			byte[] pool = new byte[1024];
			packet = new DatagramPacket(pool, 0, pool.length, InetAddress.getByName("127.0.0.1"), 10011);
			packet.setData("我是T2".getBytes());
			
			socket.send(packet);
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/96871.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!