【Java笔记】网络编程

来源:互联网 发布:dd for windows 64位 编辑:程序博客网 时间:2024/05/16 17:00

TCP编程 -(TransmissionControl Protocol)


Socket类:客户端通过它与服务器端建立连接并通信

ServerSocket类:服务器端通过它与客户端建立连接

 

Client

public class TCPClient{public static void main(String[] args){Socket s = new Socket("127.0.0.1",7777);OutputStream os = s.getOutputStream();DataOutputStream dos = new DataOutputStream(os);dos.writeUTF("HELLO server !");dos.flush();dos.close();s.close();}}

Server

public class TCPServer{public static void mian(String[] args){ServerSocket ss = new ServerSocket(7777);while (true) {Socket s = ss.accept();DataInputStream dis = new DataInputStream(s.getInputStream());System.out.println(dis.readUTF());  dis.close();  s.close();  }}}


 

 

UDP编程 -(User DatagramProtocol)


DatagramSocket类:用于收发数据报

DatagramPacket类:封装了IP地址,端口号和数据内容的数据报,数据的载体

 

Client

public class TestUDPClient{public static void main(String[] args){long n = 10000L;ByteArrayOutputStream baos = new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream(baos);dos.writeLong(n);byte[] buf = baos.toByteArray();DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",5678));DatagramSocket ds = new DatagramSocket(9999);ds.send(dp);ds.close();}}


Server

public class TestUDPServer{public static void main(String[] args){byte buf[] = new byte[1024];DatagramPacket dp = new DatagramPacket();DatagramSocket ds = new DatagramSocket();while (true) {ds.receive(dp);ByteArrayInputStream bais = new ByteArrayInputStream(buf);DataInputStream dis = new DataInputStream(bais);System.out.print(dis.readLong());}}}



小结


TCP编程是面向连接的,基于流的传输。可靠性很高,但是需要很多资源,开销很大。

UDP编程是采用直接发送数据报,不需要连接。速度很快,但是不保证完全接收。

1 0
原创粉丝点击