基于TCP和UDP的Socket编程事例代码

来源:互联网 发布:竹书纪年 知乎 编辑:程序博客网 时间:2024/05/16 00:25

首先是基于TCP的socket编程

package primary;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import org.junit.Test;public class TCPSocket {@Testpublic void Client() {Socket s = null;OutputStream os = null;InputStream is = null;try {s = new Socket(InetAddress.getByName("127.0.0.1"), 8989);// 客户端Socket,指定服务端IP和端口号os = s.getOutputStream();os.write("你好,服务器!".getBytes()); // 要输出的数据s.shutdownOutput(); // 数据输出完毕is = s.getInputStream();int len = 0;byte[] b = new byte[8];while ((len = is.read(b)) != -1) {System.out.print(new String(b, 0, len));}} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}if (s != null) {try {s.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void Server() {ServerSocket ss = null;Socket s = null;OutputStream os = null;try {ss = new ServerSocket(8989); // 服务端Socket指定端口即可s = ss.accept();InputStream is = s.getInputStream();byte[] b = new byte[8];int len = 0;while ((len = is.read(b)) != -1) {System.out.print(new String(b, 0, len));}os = s.getOutputStream();os.write("我已收到你的信息".getBytes());s.shutdownOutput();} catch (IOException e) {e.printStackTrace();} finally {if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}if (s != null) {try {s.close();} catch (IOException e) {e.printStackTrace();}}if (ss != null) {try {ss.close();} catch (IOException e) {e.printStackTrace();}}}}}
基于UDP的Socket编程

package primary;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import org.junit.Test;public class UDPSocket {@Testpublic void Send() {// 发送端DatagramSocket ds = null; // 数据报套接字try {ds = new DatagramSocket();byte[] b = "你好,我是要传输的数据".getBytes();// 数据报包,包含要发送的数据,发送的地址及程序端口号DatagramPacket dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 8989);ds.send(dp);} catch (IOException e) {e.printStackTrace();} finally {if (ds != null) {ds.close();}}}@Testpublic void receive() {// 接收端DatagramSocket ds = null;try {ds = new DatagramSocket(8989);byte[] b = new byte[1024];DatagramPacket dp = new DatagramPacket(b, 0, b.length);ds.receive(dp);System.out.println(new String(b));} catch (IOException e) {e.printStackTrace();} finally {if (ds != null) {ds.close();}}}}



TCP传输需经历“三次握手”,安全,但效率要低于UDP

0 0
原创粉丝点击