基于TCP/IP协议的通信
- TCP/IP协议
- TCP/IP协议.会在通信两端建立连接(虚拟连接),用于发送和接收数据
- TCP/IP协议是一种可靠的网络协议,它通过重发机制来保证这种可靠性
通信的实现
ServerSocket用来监听来自客户端的连接,当没有连接时,它处于阻塞状态
客户端使用Socket连接到指定的服务器
基于UDP协议的通信
- UDP协议
- UDP协议不会在通信两端建立连接(虚拟链路),而是直接发送连接
- UDP协议是一种不可靠的网络协议,但是这种协议的通信效率非常高
- 通信的实现
- DatagramSocket用于两端的通信,它不负责 维护状态,不产生io流,仅仅是发送或接受数据包
- DatagramPacket代表数据包
InetAddress
/** * * InetAddressDemo * * */ public class InetAddressDemo { public static void main(String[] args) throws IOException { InetAddress baidu = InetAddress.getByName("www.baidu.com"); System.out.println(baidu); System.out.println(baidu.getHostAddress());//获取主机地址 System.out.println(baidu.isReachable(1000));//是否可达 System.out.println("===================================================================================="); InetAddress local = InetAddress.getByAddress(new byte[]{127, 0, 0, 1}); System.out.println(local.getHostName());//获取主机名 System.out.println(local.isReachable(1000));//是否可达 } }
案例演示 (简易聊天室)
package javaserver.TcpServer; import JAVAClient.TcpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class tcpServer { public static ExecutorService threadPool= Executors.newFixedThreadPool(10); public static List<Socket> socketList= Collections.synchronizedList(new ArrayList<>()); public static void main(String[] args) { // // try { // // //接受客户端的请求 // ServerSocket serverSocket=new ServerSocket(9000); // while (true){ // Socket socket = serverSocket.accept();//封装了一些客户端的信息 // System.out.println("请求;" + socket.toString()); // // PrintStream ps=new PrintStream(socket.getOutputStream()); // ps.println("welcome "+ socket.getInetAddress().getHostAddress()); // socket.close(); // } // // } catch (Exception e) { // e.printStackTrace(); // } // } try { ServerSocket serverSocket = new ServerSocket(9000); while (true){ Socket socket = serverSocket.accept(); socketList.add(socket); threadPool.submit(new ThreadTask(socket)); } } catch (Exception e) { e.printStackTrace(); } } } class ThreadTask implements Runnable{ private Socket socket; private BufferedReader reader; public ThreadTask(Socket socket) { this.socket = socket; try { this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { String line; while ((line=reader.readLine())!=null){ for (Socket client: tcpServer.socketList){ String from=socket.getInetAddress().getHostAddress()+":::"+socket.getPort(); String content= from+"说"+line; new PrintStream(client.getOutputStream()).println(content); } } } catch (Exception e) { e.printStackTrace(); } } }
package JAVAClient; import java.io.*; import java.net.Socket; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TcpClient { public static ExecutorService threadPool= Executors.newFixedThreadPool(3); public static void main(String[] args) throws IOException { // Socket socket=new Socket("127.0.0.1",9000); // BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream())); // String s = br.readLine(); // System.out.println(s); Socket socket=new Socket("127.0.0.1",9000); threadPool.submit(new ReadTask(socket)); threadPool.submit(new WriteTask(socket)); } } class ReadTask implements Runnable{ private Socket socket; private BufferedReader reader; public ReadTask(Socket socket) { this.socket = socket; try { this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { String line; while ((line=reader.readLine())!=null){ System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } } class WriteTask implements Runnable{ private Socket socket; private PrintStream writer; public WriteTask(Socket socket) { this.socket = socket; try { writer=new PrintStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { Scanner scanner = new Scanner(System.in); String line; while ((line=scanner.nextLine())!=null){ writer.println(line); } } }
UDP 演示
服务端
package javaserver.TcpServer; import java.net.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class UdpServer { public static ExecutorService threadPool= Executors.newFixedThreadPool(10); public static List<InetSocketAddress> addressesList=new ArrayList<>(); public static void main(String[] args) { try { DatagramSocket socket=new DatagramSocket(9001); // 随时通知 threadPool.submit(new SendTask(socket)); //接受访问 并且记录 byte[] buffer=new byte[1024]; DatagramPacket packet=new DatagramPacket(buffer,buffer.length); while (true){ socket.receive(packet); addressesList.add((InetSocketAddress) packet.getSocketAddress()); } } catch (Exception e) { e.printStackTrace(); } } } class SendTask implements Runnable{ private DatagramSocket socket; public SendTask(DatagramSocket socket) { this.socket = socket; } @Override public void run() { try { Scanner scanner = new Scanner(System.in); String line; while ((line= scanner.nextLine())!=null){ for (InetSocketAddress isa:UdpServer.addressesList){ byte[] buffer=line.getBytes(); DatagramPacket packet=new DatagramPacket(buffer,buffer.length,isa.getAddress(),isa.getPort()); socket.send(packet); } } } catch (Exception e) { e.printStackTrace(); } } }
客户端
package JAVAClient; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class UdpClient { public static ExecutorService threadPool= Executors.newFixedThreadPool(3); public static void main(String[] args) { try { DatagramSocket socket=new DatagramSocket(); // 注册 DatagramPacket packet=new DatagramPacket(new byte[]{1},1, InetAddress.getByName("127.0.0.1"),9001); socket.send(packet); // 接收 threadPool.submit(new ReceiveTask(socket)); } catch (Exception e) { e.printStackTrace(); } } } class ReceiveTask implements Runnable{ private DatagramSocket socket; public ReceiveTask(DatagramSocket socket) { this.socket = socket; } @Override public void run() { try { byte[] buffer=new byte[1024]; DatagramPacket packet=new DatagramPacket(buffer,buffer.length); while (true){ socket.receive(packet); String line =new String(packet.getData(),0, packet.getLength()); System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } }
总结
本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注自学编程网的更多内容!
- 本文固定链接: https://zxbcw.cn/post/218873/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)