UDP
将数据及源和目的封装成数据包,不需要建立连接
每个数据包的大小限制在64K内
因无连接,是不可靠协议
不需要建立连接,速度快
TCP
建立连接,形成传输数据的通道
在连接中可以进行大数据量的传输
通过三次握手完成连接,是可靠协议
必须建立连接,效率会比udp稍低
UDP网络聊天示例
import java.io.*;
import java.net.*;
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=br.readLine())!=null){
if("886".equals(line)){
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.1"),10000);
ds.send(dp);
}
}catch(Exception e){
throw new RuntimeException("出现错误");
}
}
}
class Rece implements Runnable{
private DatagramSocket ds;
public Rece(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+ip+"::"+data);
}
}catch (Exception e){
throw new RuntimeException("接收出现错误");
}
}
}
//启动程序
class ChatDemo {
public static void main(String[] args) throws Exception{
DatagramSocket sendSocket = new DatagramSocket();//发送端可以不指定端口
DatagramSocket receSocket = new DatagramSocket(10000);//接收端必须指定接收端口
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
class TcpClient{
public static void main(String[] args){
//创建客户端的socket服务。指定目的主机和端口
Socket s = new Socket("192.168.1.1",10000);
//为了发送数据,应该获取socket流中的输出流。
OutputStream out = s.getOutputStream();
//s.getInputStream();
out.write("sdfsdfsd".getBytes());
s.close();
}
}
class TcpServer{
public static void main(String[] args){
//建立服务端socket服务。监听一个端口
ServerSocket ss = new ServerSocket(10000);
//通过accept方法获得连接过来的客户端对象。
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+".....connected");
//获取客户端发送过来的数据,那么要使用客户对象的读取流来读取数据。
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
s.close();//关闭客户端
ss.close();//关闭服务端
}
}