1.网络通信要素
2.IP
3.端口号
4.通信协议
TCP : 打电话
UDP : 发短信 , 发电报
4.1 TCP
public class TCPtest { //客户端发送消息给服务端 , 服务端将信息显示在控制台 //客户端 @Test public void client() { Socket socket = null; OutputStream outputStream = null; try { //获取服务端的socket InetAddress address = InetAddress.getByName("127.0.0.1"); socket = new Socket(address, 8899); //通过socket 获取输出流 , 发送信息 outputStream = socket.getOutputStream(); outputStream.write("你好,我是客户端mm".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } //服务端 @Test public void server() { ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try { //创建serverSocket serverSocket = new ServerSocket(8899); //接收客户端的socket socket = serverSocket.accept(); //创建接受流 inputStream = socket.getInputStream(); //打印信息 byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[5]; int len; while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } System.out.println(byteArrayOutputStream.toString()); } catch (IOException e) { e.printStackTrace(); } finally { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4.2 UDP
public class UDPtest { //测试用UDP协议 发送和 接收数据 //发送端 @Test public void sender()throws IOException { DatagramSocket datagramSocket = new DatagramSocket(); String str = "我是UDP方式发送的数据!"; InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(str.getBytes(), 0, str.getBytes().length, address, 9090); //发送 datagramSocket.send(packet); //关闭socket datagramSocket.close(); } //接收端 @Test public void receiver()throws IOException{ DatagramSocket socket = new DatagramSocket(9090); byte[] buffer = new byte[100]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); //接收 socket.receive(packet); System.out.println(new String(packet.getData(),0,packet.getLength())); //关闭 socket.close(); } }
5.URL
//从Tomcat中下载图片 @Test public void test()throws IOException { URL url = new URL("http://localhost:8080/examples/picture.jpg"); //获取链接 HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection(); urlConnection.connect(); //获取输入 , 输出流 InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("picture1.jpg"); //传输数据 byte[] buffer = new byte[5]; int len; while ((len=inputStream.read(buffer))!=-1){ fileOutputStream.write(buffer,0,len); } System.out.println("下载完成!"); //关闭资源 fileOutputStream.close(); inputStream.close(); urlConnection.disconnect(); }