java——TCP和UDP

来源:互联网 发布:数据精灵ios破解版 编辑:程序博客网 时间:2024/06/05 11:58

    在现有的网络中通讯方式协议有两种:TCP和UDP

TCP

是专门设计用于不可靠的的因特网上提供可靠的、端到端的字节流通信的协议,它是一种面向连接的协议,TCP连接是字节流而非报文流。

TCP协议就像打电话一样,接通以后有讲话有应答。

UDP

向应用程序提供了一种发送封装的原始IP数据报的方法、并且发送时无需建立连接,是一种不可靠的连接。

UDP协议就像发电报一样,发出去后就不在去考虑对方收到没有收到。

根据TCP/IP的模式图可以看出这两种协议的关系。


socket

socket在TCP/IP的模式图中的什么位置呢?


Socket是应用层与传输层的中间软件抽象层,它把复杂的TCP/IP协议隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。


TCP socket编程 

服务器端初始化socket以后,会对端口进行监听,调用accept()进行阻塞,这时如果有客户度初始化 socket,并连接服务器,连接成功后,客户就会发送数据请求,服务器端会接受并处理请求然后把回应数据发送给客户端,客户端读取数据,最后关闭连接,一次交互结束。

客户端

import java.net.*;import java.io.*;public class TCPClient {public static void main(String[] args) throws Exception {Socket s = new Socket("127.0.0.1", 6666);OutputStream os = s.getOutputStream();DataOutputStream dos = new DataOutputStream(os);Thread.sleep(30000);dos.writeUTF("hello server!");dos.flush();dos.close();s.close();}}

服务器端

import java.net.*;import java.io.*;public class TCPServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(6666);while(true) {Socket s = ss.accept();System.out.println("a client connect!");DataInputStream dis = new DataInputStream(s.getInputStream());System.out.println(dis.readUTF());dis.close();s.close();}}}

UDP socket编程

UPD的编程中,服务器端接受数据后不再进行将数据发送给客户度。

客户度

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

服务器端

import java.net.*;import java.io.*;public class TestUDPServer{public static void main(String args[]) throws Exception{byte buf[] = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);DatagramSocket ds = new DatagramSocket(5678);while(true){ds.receive(dp);ByteArrayInputStream bais = new ByteArrayInputStream(buf);DataInputStream dis = new DataInputStream(bais);System.out.println(dis.readLong());}}}

    总结,TCP类似于程序编程中的函数,当调用函数是必须有一个返回值给调用它的程序。而UDP有点类似于过程,程序调用这个过程以后不需要告诉程序调用后的结果是什么。

1 0
原创粉丝点击