En el zócalo en Java

TCP y UDP

TCP y UDP ellos se encuentran en la capa de transporte en la OSI en capas para proporcionar soporte para la capa de aplicación. TCP es una necesidad protocolos de transporte de red con conexión, el cliente y el servidor para establecer una conexión estable a los datos se transmitan entre sí. El UDP es un protocolo de transporte sin conexión a la red, el cliente y el servidor no necesita establecer una conexión, el cliente envía paquetes independientemente de que el otro existe, puede ser enviado.

TCP

TCP ( Transmission Control Protocol protocolo de control de transmisión) es una conexión estable y fiable, el cliente y el servidor antes de establecer una conexión requiere de tres vías . Aunque conexión estable, pero ya que se complica el proceso de transferencia de datos, lo que resulta en la eficiencia de transmisión de la UDP mucho más bajo. Por lo general requieren datos precisos utilizados en la escena, tales como transferencia de archivos, visualización de la página web, la entrega de mensajes y similares. En java del TCP mediante Socket和ServerSocketlogrado dos clases TCP función.

Socket cliente 1.TCP
//客户端类
public class TestSocketclient {
	//构造方法
	public TestSocketclient(String ip,int port){
		try {
			@SuppressWarnings("resource")
			Socket socket = new Socket(ip,port);//指明服务器ip和端口号
			//向服务器发送消息
			String data = "hello server";
			OutputStream os = socket.getOutputStream();//输出流就是向服务器发送数据的流
			os.write(data.getBytes());
			
			//接收来自服务器的消息
			InputStream is = socket.getInputStream();//输入流就是接收来自服务器数据的流
			byte[] serverinfo = new byte[1024];
			int n = -1;
			while((n=is.read(serverinfo))!=-1){
				String string = new String(serverinfo,0,n);
				System.out.println(string);
			}
			
			os.close();
			is.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//启动方法,应该让服务器端先启动
	public static void main(String[] args) {
		try {
			new TestSocketclient(InetAddress.getLocalHost().getHostAddress(),8888);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
}
ServerSocket servidor 2.TCP
//服务器端
public class TestServerSocket {
	//构造方法
	public TestServerSocket(int port){
		try {
			ServerSocket ss = new ServerSocket(port);//监听端口
			//接收来自客户端的数据,该方法accept()是阻塞方法,直到接到请求才往下执行。
			Socket accept = ss.accept();
			InputStream is = accept.getInputStream();
			byte[] packet = new byte[1024];
			int n = is.read(packet);
			String string = new String(packet,0,n);
			System.out.println(string);
			//向客户端发送消息
			OutputStream os = accept.getOutputStream();
			os.write("hello client".getBytes());
			
			os.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//启动方法
	public static void main(String[] args) {
		new TestServerSocket(8888);
	}
}

UDP

UDP ( el Protocolo de datagramas de usuario ) Protocolo de datagrama de usuario es un protocolo de transmisión de datos menos estable, que a menudo pierden paquetes durante la transmisión, pero sin perder demasiado, no afectan a la integridad general de los datos. Parece UDP ya la inestabilidad, sino también la pérdida de datos, ¿por qué seguir siendo hoy, no se ha abandonado? Eso es porque tiene un índice de transferencia muy extraordinaria. También se usa ampliamente, tales como juegos en línea, aunque no todos los datos son UDP (como los atributos del jugador), pero una gran proporción de sus componentes, herramientas de chat QQ, llamadas de vídeo en tiempo real, videoconferencias, etc. Utilizando el java DatagramSocketclase de implementación UDP función.

1.UDP cliente
//客户端
public class TestUDPclient {
	//构造方法
	public TestUDPclient(String ip,int port){
		
		try {
			//客户端不用在socket上指明ip和port
			DatagramSocket ds = new DatagramSocket();
			
			byte[] buf = "nihao 服务器".getBytes();
			int length = buf.length-4;//必须是绑定数据的大小,不能大于,可以小于,不能为负
			InetAddress address = InetAddress.getByName(ip);
			//在数据报上指明服务器的ip和port
			DatagramPacket dp = new DatagramPacket(buf,length, address, port);
			//发送数据
			ds.send(dp);
			//关闭套接字
			ds.close();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//启动方法
	public static void main(String[] args) {
		new TestUDPclient("localhost",7777);
	}
}
servidor 2.UDP
//服务器端
public class TestUDPServer {
	//构造方法
	public TestUDPServer(int port){
		try {
			
			DatagramSocket ps = new DatagramSocket(port);//监听port端口是否有请求
			byte[] b= new byte[1024];
			DatagramPacket pd = new DatagramPacket(b, 1024);//准备一个空包接收数据用
			//接收数据
			ps.receive(pd);
			//得到数据并打印
			byte[] data = pd.getData();
			System.out.println(new String(data,0,data.length));
			//关闭套接字
			ps.close();
		} catch (Exception e) {
		}
	}
	//启动方法
	public static void main(String[] args) {
		new TestUDPServer(7777);
	}

}
3. Suplemento

UDP en uso DatagramSocketcuando los implementos de clase del cliente y el servidor están utilizando la misma clase, que se distinguen por el servidor y el cliente configure si el número de puerto e IP. Siempre y cuando la configuración del puerto e IP DatagramSocket puede actuar como un servidor. Pero la misma dirección IP que el extremo inferior de la consigna no puede, o informará al puerto ocupado por la anomalía. 谁先接收数据谁先启动Los siguientes son ilustrativos:

  • cliente
public class TestUDPclient {
	
	public TestUDPclient(String ip,int port){
		
		try {
			//作为端口号为8888的服务器端
			DatagramSocket ds = new DatagramSocket(8888);
			
			byte[] buf = "nihao 服务器".getBytes();
			int length = buf.length;
			InetAddress address = InetAddress.getByName(ip);
			DatagramPacket dp = new DatagramPacket(buf,length, address, port);
			
			ds.send(dp);
			//发送后再来接收数据
			DatagramPacket dp2 = new DatagramPacket(new byte[1024], 1024);
			ds.receive(dp2);
			byte[] data = dp2.getData();
			System.out.println(new String(data,0,data.length));
			
			ds.close();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new TestUDPclient("localhost",7777);
	}
}
  • Del lado del servidor
public class TestUDPServer {
	
	public TestUDPServer(int port){
		try {
			//作为端口号为7777的服务器端
			DatagramSocket ps = new DatagramSocket(port);
			byte[] b= new byte[1024];
			DatagramPacket pd = new DatagramPacket(b, 1024);
			
			ps.receive(pd);
			
			byte[] data = pd.getData();
			System.out.println(new String(data,0,data.length));
			//接收完数据再发送,发送给本地端口号为8888的服务器端
			DatagramPacket dp2 = new DatagramPacket("nihao".getBytes(),5,InetAddress.getByName("localhost"),8888);
			ps.send(dp2);
			
			ps.close();
		} catch (Exception e) {
		}
	}
	
	public static void main(String[] args) {
		new TestUDPServer(7777);
	}

}
Publicado seis artículos originales · ganado elogios 2 · Vistas 510

Supongo que te gusta

Origin blog.csdn.net/wl12346/article/details/104840355
Recomendado
Clasificación