UDP模式聊天
//client (前台)
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Client { //UDP聊天 public static void main(String[] args) throws Exception { //创建字符串 String word ="Hello"; //将字符串转化成字节 byte[] bytes = word.getBytes(); DatagramSocket socket =new DatagramSocket(); DatagramPacket packet =new DatagramPacket(bytes, 0,bytes.length,InetAddress.getByName("localhost"),50000); socket.send(packet); } }
//server (后台)
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class Server { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.out.println("开启后台"); //接受或发送数据报的套结字 DatagramSocket socket =new DatagramSocket(50000); byte [] bytes =new byte[1024]; //表是存放数据的数据表 DatagramPacket packet =new DatagramPacket(bytes, 0,bytes.length); socket.receive(packet); byte[] data = packet.getData(); String temp =new String(data,0,data.length); System.out.println(temp); } }