java基础之 网络编程

1. 基本知识

网络通讯三要素:

IP InetAddress

PORT

网络协议 UDP/TCP

网络参考模型:

OSI:七层

TCP/IP: 应用层 HTTP FTP

传输层 TCP UDP

网际层 IP 

主机至网络层


2.IP地址对象InetAddress

<span style="font-size:14px;">	//获取本地IP地址对象
	InetAddress address = InetAddress.getLocalHost();  
	//mlu-PC/172.16.22.55
	System.out.println(address);    
	//172.16.22.55
	System.out.println(address.getHostAddress());    
	//mlu-PC
	System.out.println(address.getHostName());    
	
	//根据域名或IP获取IP地址对象
	InetAddress address = InetAddress.getByName("172.16.22.55");
	InetAddress address = InetAddress.getByName("www.baidu.com");
	//180.97.33.108
	System.out.println(address.getHostAddress());
	//www.baidu.com
	System.out.println(address.getHostName());</span>

3.UDP TCP

UDP:

1)将数据及源和目的封装成数据包,不需要建立连接

2)每个数据包的大小限制在64k内

3)因无连接,是不可靠协议

4)不需要建立连接,速度快

5)分为发送端和接收端 DatagramSocket

TCP:

1)建立连接,形成传输数据的通道

2)在连接中进行大数据量传输

3)通过三次握手完成连接,是可靠协议

4)必须建立连接,效率会稍低

5)分为客户端和服务端 Socket ServerSocket


4.Socket

1)Socket就是为网络服务提供的一种机制

2)通信的两端都有Socket

3)网络通信其实就是Socket间的通信

4)数据在两个Socket间通过IO传输


5.UDP传输

5.1 UDP发送

	/**
	 * 1.建立UDPSocket服务
	 * 2.提供数据,并将数据封装到数据包中
	 * 3.通过socket的发送功能,将数据包发送出去
	 * 4.关闭资源
	 */
	public class UdpSend {
		public static void main(String[] args) throws Exception {
			//1.创建UDP服务,通过DatagarmSocket对象
			DatagramSocket ds = new DatagramSocket();
			//2.提供数据,并将数据封装到数据包中
			byte[] data = "I am Comming".getBytes();
			DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("172.16.22.55"), 10000);
			//3.通过socket的发送功能,将数据包发送出去
			ds.send(dp);
			//4.关闭资源
			ds.close();
		}
	}

5.2 UDP接收

	/**
	 * 1.建立UDPSocket服务,通常指定监听端口
	 * 2.定义数据包,存储接收到的数据信息
	 * 3.通过socket的接收功能,将数据存入数据包
	 * 4.取出数据
	 * 5.关闭资源
	 */
	public class UdpReceive {
		public static void main(String[] args) throws Exception {
			//1.建立UDPSocket服务
			DatagramSocket ds = new DatagramSocket(10000);
			
			//2.定义数据包,存储接收到的数据信息
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf, buf.length);
			
			//3.通过socket的接收功能,将数据存入数据包
			ds.receive(dp);
			
			//4.取出数据
			String ip = dp.getAddress().getHostAddress();
			int port = dp.getAddress().getPort();
			String data = new String(dp.getData(),0,dp.getLength());
			
			//5.关闭资源
			ds.close();			
		}
	}

5.3 UDP通过键盘输入

	//接收端
	public class UdpReceive {
		public static void main(String[] args) throws Exception {
			//1.建立UDPSocket服务
			DatagramSocket ds = new DatagramSocket(10000);
			//服务器一直启动
			while(true){
				//2.定义数据包,存储接收到的数据信息
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				//3.通过socket的接收功能,将数据存入数据包
				ds.receive(dp);
				//4.取出数据
				String ip = dp.getAddress().getHostAddress();
				int port = dp.getPort();
				String data = new String(dp.getData(),0,dp.getLength());
				System.out.println("ip:"+ip + "; port:" +port +"; data:" +data);
			}
		}
	}
	
	//发送端,输入886结束
	public class UdpSend {
		public static void main(String[] args) throws Exception {
			//1.创建UDP服务,通过DatagarmSocket对象
			DatagramSocket ds = new DatagramSocket(10001);
			//2.从键盘输入数据
			BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			while((line = buffer.readLine()) != null){
				if("886".equals(line)){
					break;
				}
				byte[] data = line.getBytes();
				DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("172.16.22.55"), 10000);
				//3.通过socket的发送功能,将数据包发送出去
				ds.send(dp);
			}
			//4.关闭资源
			ds.close();
		}
	}
	

5.4 UDP聊天

	public class UdpChat {
		public static void main(String[] args) throws Exception {
			DatagramSocket sendSocket = new DatagramSocket();
			DatagramSocket receSocket = new DatagramSocket(20000);
			
			new Thread(new send(sendSocket, "172.16.22.55", 20001)).start();
			new Thread(new receive(receSocket)).start();
		}
	}
	public class UdpChat2 {
		public static void main(String[] args) throws SocketException {
			DatagramSocket sendSocket = new DatagramSocket();
			DatagramSocket receSocket = new DatagramSocket(20001);
			
			new Thread(new send(sendSocket, "172.16.22.55", 20000)).start();
			new Thread(new receive(receSocket)).start();
		}
	}

	class send implements Runnable{
		private DatagramSocket ds;
		private String ip;
		private int port;
		public send(DatagramSocket ds, String ip, int port){
			this.ds = ds;
			this.ip = ip;
			this.port = port;
		}
		@Override
		public void run(){
			//从键盘接收数据
			BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			try {
				while((line = buffer.readLine()) != null){
					if("886".equals(line)){
						break;
					}
					byte[] buf = line.getBytes();
					//组建包
					DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port);
					ds.send(dp);
				}
			} catch (Exception ex) {
			}
		}
	}

	class receive implements Runnable{
		private DatagramSocket ds;
		public receive(DatagramSocket ds){
			this.ds = ds;
		}
		@Override
		public void run(){
			try {
				while(true){
					//创建包接收数据
					byte[] buf = new byte[1024];
					DatagramPacket dp = new DatagramPacket(buf, buf.length);
					ds.receive(dp);
					
					//取出数据
					String ip = dp.getAddress().getHostAddress();
					int port = dp.getPort();
					String data = new String(dp.getData(),0,dp.getLength());
					System.out.println(ip + ":" +data);
				}
			} catch (Exception ex) {
			}
		}
	}
	

6.1 TCP 传输

/**
 *
 * 客户端:在建立socket服务时,就要有服务端存在,并连接成功,形成通路后,在该通道内进行数据的传输。
 */
public class Tcp_Client {
    public static void main(String[] args) throws Exception {
        System.out.println("client");
        Socket s = new Socket("172.16.22.55",10010);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        BufferedReader buffIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        
        //向服务端发送消息
        String line = null;
        while((line = reader.readLine()) != null){
            if("over".equals(line)){
                break;
            }
            buffOut.write(line);
            buffOut.newLine();
            buffOut.flush();
            System.out.println("to server ");

            //读取服务端返回的消息
            String returnStr = null;
            while((returnStr = buffIn.readLine())!=null){
                System.out.println("from server: " + returnStr);
            }
        }
        reader.close();
        s.close();
    }
}
/**
 *
 * 服务端,监听一个端口
 */
public class Tcp_Server {
    public static void main(String[] args) throws IOException {
        System.out.println("server");
        ServerSocket ss = new ServerSocket(10010);
        Socket s = ss.accept();
        //获取客户端的ip地址
        String address = s.getInetAddress().getHostAddress();
        
        //socket输入流
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        
        //socket输出流
        BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        
        String sIn = null;
        while((sIn = bufIn.readLine()) != null){
            System.out.println(address + " : " + sIn);
            
            //将字符串改为大写后返回
            bufOut.write(sIn.toUpperCase());
            bufOut.newLine();
            bufOut.flush();
            
            System.out.println("flush over");
        }
        s.close();
        ss.close();
    }
}


6.2 TCP上传文件
public class TcpFileUpload_Client {
    public static void main(String[] args) throws Exception {
        System.out.println("client");
        Socket s = new Socket("172.16.22.55",10020);
        
        //读取上传的文件
        BufferedReader reader = new BufferedReader(new FileReader("d:\\aa.txt"));
        
        //向服务端传输文件 PrintWriter true代表自动flush
        PrintWriter buffOut = new PrintWriter(s.getOutputStream(), true);
        
        //接收服务端的回复
        BufferedReader buffIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        
        //向服务端发送消息
        String line = null;
        while((line = reader.readLine()) != null){
            buffOut.println(line);
            System.out.println("to server ");
        }

        //读取服务端返回的消息
        String returnStr =  buffIn.readLine();
        System.out.println(returnStr);
        
        reader.close();
        s.close();
    }
}

public class TcpFileUpload_Server {
    public static void main(String[] args) throws IOException {
        System.out.println("server");
        ServerSocket ss = new ServerSocket(10020);
        Socket s = ss.accept();
        //获取客户端的ip地址
        String address = s.getInetAddress().getHostAddress();
        System.out.println(address + " connect");
            
        //socket输入流
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        
        //socket输出流
        PrintWriter bufOut = new PrintWriter(new FileWriter("d:\\newText.txt"), true);
        
        //读取输入流信息
        String sIn = null;
        while((sIn = bufIn.readLine()) != null){
            if("over".equals(sIn)){
                System.out.println("flush over");
                break;
            }
            bufOut.println(sIn);
        }
        
        //返回信息给客户端
        PrintWriter bufWriter = new PrintWriter(s.getOutputStream(), true);
        bufWriter.println("success");
        
        bufOut.close();
        s.close();
        ss.close();
    }
}

6.3 TCP上传图片

public class TcpPicUpload_Client {
    public static void main(String[] args) throws Exception {
        System.out.println("client");
        Socket s = new Socket("172.16.22.55",10030);
        
        //读取上传的文件
        FileInputStream fis = new FileInputStream("d:\\aa.jpg");
        
        //向服务端传输文件
        OutputStream buffOut = s.getOutputStream();
        
        //向服务端发送消息
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1){
            buffOut.write(buf,0,len);
        }
        //告诉服务器已经读完
        s.shutdownOutput();
        
        //接收服务端的回复
        InputStream sr = s.getInputStream();
        //读取服务端返回的消息
        byte[] bufIn = new byte[1024];
        int num = sr.read(bufIn);
        System.out.println(new String(bufIn,0,num));
        
        fis.close();
        s.close();
    }
}

public class TcpPicUpload_Server {
    public static void main(String[] args) throws IOException {
        System.out.println("server");
        ServerSocket ss = new ServerSocket(10030);
        Socket s = ss.accept();
        //获取客户端的ip地址
        String address = s.getInetAddress().getHostAddress();
        System.out.println(address + " connect");
            
        //socket输入流
        InputStream buffIn = s.getInputStream();
        
        FileOutputStream fos = new FileOutputStream("d:\\newPic.jpg"); 
        
        //socket输出流
        OutputStream buffOut = s.getOutputStream();
        
        //读取输入流信息
        byte[] buff = new byte[1024];
        int len = 0;
        while((len = buffIn.read(buff)) != -1){
            fos.write(buff,0,len);
        }
        
        //返回信息给客户端
        buffOut.write("success".getBytes());
        
        fos.close();
        s.close();
        ss.close();
    }
}

6.4 TCP并发上传图片

public class TcpPicUpload_Server_multi {
    public static void main(String[] args) throws IOException {
        System.out.println("server");
        ServerSocket ss = new ServerSocket(10040);
        while(true){
            Socket s = ss.accept();
            new Thread(new UploadPicThread(s)).start();
        }
    }
}
class UploadPicThread implements Runnable{
    private Socket s;

    public UploadPicThread(Socket s) {
        this.s = s;
    }
    
    @Override
    public void run() {
        //获取客户端的ip地址
        String address = s.getInetAddress().getHostAddress();
        System.out.println(address + " connect");
        FileOutputStream fos = null; 
        //socket输入流
        InputStream buffIn;
        
        //socket输出流
        OutputStream buffOut = null;
        try {
            buffIn = s.getInputStream();
            long l = System.currentTimeMillis();
            
            fos = new FileOutputStream("d:\\"+ String.valueOf(l) + ".jpg"); 
            buffOut = s.getOutputStream();
        
            //读取输入流信息
            byte[] buff = new byte[1024];
            int len = 0;
            while((len = buffIn.read(buff)) != -1){
                fos.write(buff,0,len);
            }

            //返回信息给客户端
            buffOut.write("success".getBytes());

            fos.close();
            s.close();
        } catch (IOException ex) {
        }
    }
}

6.5 URL && URLConnection

	public static void main(String[] args) throws MalformedURLException, IOException {
        URL url = new URL("http://localhost:8080/HelloNet/index.jsp?name=haha");
        //获取此url的协议名称 http
        System.out.println("url.getProtocol() : " + url.getProtocol());
        //获取此url的主机名 localhost
        System.out.println("url.getHost() : " + url.getHost());
        //获取此url的端口号 8080
        System.out.println("url.getPort() : " + url.getPort());
        //获取此url的路径部分 /HelloNet/index.jsp
        System.out.println("url.getPath() : " + url.getPath());
        //获取此url的文件名 /HelloNet/index.jsp?name=haha
        System.out.println("url.getFile() : " + url.getFile());
        //获取此url的查询部分 name=haha
        System.out.println("url.getQuery() : " + url.getQuery());
        
        //通过URLConnection向服务器发送请求
        URLConnection urlConn = url.openConnection();
        
        //获取服务器返回的文件内容
        InputStream in = urlConn.getInputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        if((len = in.read(buf)) != -1){
            System.out.println(new String(buf, 0, len));
        }
    }







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值