首页 > 代码库 > java的TCP和UDP编程
java的TCP和UDP编程
TCP
客户端:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class MyClient { public static void main(String[] args) throws Exception{ Socket socket = null; BufferedReader in = null; PrintWriter out = null; BufferedReader input = null; // 请求指定ip和端口号的服务器 socket = new Socket("127.0.0.1",3333); while(true){ in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // 接收控制台的输入 input = new BufferedReader(new InputStreamReader(System.in)); // out.println("this is client info!"); String info = input.readLine(); out.println(info); String str = in.readLine(); System.out.println("客户端显示--》服务器的信息:" + str); } //in.close(); //out.close(); } }
服务端:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class MyServices { public static void main(String[] args) throws Exception{ ServerSocket ss = null; Socket socket = null; BufferedReader in = null; PrintWriter out = null; BufferedReader input = null; // 监听3333端口 ss = new ServerSocket(3333); // 等待接收客户端的请求 socket = ss.accept(); while(true){ // 获取连接对象的输入流 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 获取客户端的输入信息 String str = in.readLine(); input = new BufferedReader(new InputStreamReader(System.in)); System.out.println("服务器显示-->客户端输入数据:" + str); out = new PrintWriter(socket.getOutputStream(),true); // 将数据输出到客户端 // out.println("hehe"); String info = input.readLine(); out.println(info); } // in.close(); // out.flush(); // out.close(); } }
UDP
客户端:
import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPClient { public static void main(String[] args) throws Exception { DatagramSocket ds = null; DatagramPacket dp = null; byte[] buf = new byte[1024]; ds = new DatagramSocket(3333); dp = new DatagramPacket(buf, 1024); // 接收数据,放入数据报 ds.receive(dp); // 从数据报中取出数据 String info = new String(dp.getData(),0, dp.getLength()); System.out.println("接收到的信息是:" + info); } }
服务端:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPServer { public static void main(String[] args) throws Exception { DatagramSocket ds = null; DatagramPacket dp = null; // 构建发送对象 ds = new DatagramSocket(); // 将数据打包-->打成数据报 String info = "hello world!"; dp = new DatagramPacket(info.getBytes(), info.length(), InetAddress.getByName("localhost"),3333); // 发出数据报 ds.send(dp); } }
java的TCP和UDP编程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。