Java Socket 实现UDP实时聊天小案例

最近在看Socke相关的东西,因为平时工作中用到这块的东西比较少,记录一下,以后可以回顾一下。

UDP协议只管发送数据,不论服务端是否正常运行,都会发送,其特点是:效率高、不安全、容易丢包。

废话不多说,直接上代码

客户端:

package com.tz.socket.client;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * 

Title: AskClient

*

Description: 数据发送方

*

Company:

* @author UU * @date 2017年6月28日下午9:29:36 */ public class AskClient { private static final int SERVER_PORT = 8888; private static final int CLIENT_PORT = 6666; public static void main(String[] args) throws Exception { //创建套接字对象(自己的端口) DatagramSocket socket = new DatagramSocket(SERVER_PORT); // String msg = "在吗?"; //获取控制台输入信息 Scanner scanner = new Scanner(System.in); while (true) { String msg = scanner.nextLine(); DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, InetAddress.getLocalHost(), CLIENT_PORT); //发送 socket.send(packet); if ("88".equals(msg)) { break; } //接受服务端发送的信息 byte[] b = new byte[1024]; DatagramPacket packet2 = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), CLIENT_PORT); socket.receive(packet2); System.out.println("小明:"+new String(b,0,packet2.getLength())); } socket.close(); } }

 服务端:

package com.tz.socket.server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * 接受方
 * 

Title: AskServer

*

Description:

*

Company:

* @author UU * @email [email protected] * @phone 18317183091 * @date 2017年6月28日下午10:24:42 */ public class AskServer { private static final int SERVER_PORT = 6666; private static final int CLIENT_PORT = 8888; public static void main(String[] args) throws Exception { //创建套接字对象(自己的端口) DatagramSocket server = new DatagramSocket(SERVER_PORT); Scanner scanner = new Scanner(System.in); while(true){ //接受数据包,并读进数组b中 byte[] b = new byte[1024]; DatagramPacket packet = new DatagramPacket(b, b.length,InetAddress.getLocalHost(),CLIENT_PORT); server.receive(packet); System.out.println("小红:"+new String(b,0,packet.getLength())); // String callBack = "在的!"; String callBack = scanner.nextLine(); DatagramPacket packet2 = new DatagramPacket(callBack.getBytes(), callBack.getBytes().length, InetAddress.getLocalHost(),CLIENT_PORT); server.send(packet2); if ("88".equals(callBack)) { break; } } server.close(); } }

其实并没有所谓的客户端和服务端,每个类既是客户端,也是服务端,但在实际开发中,应该是客户端发送到服务器端,然后服务器端转发消息到其他客户端的过程。

你可能感兴趣的:(JAVA)