java基于UDP實現(xiàn)在線聊天功能
本文實例為大家分享了java基于UDP實現(xiàn)在線聊天的具體代碼,供大家參考,具體內(nèi)容如下
效果圖:


一、學習UDP的簡單使用步驟
接收端:
DatagramSocket socket = null;
? ? ? ? try {
? ? ? ? ? ? //1.開啟自己的端口(客戶端連接的端口)
? ? ? ? ? ? socket = new DatagramSocket(9999);
? ? ? ? ? ? //2.接收數(shù)據(jù)
? ? ? ? ? ? byte[] buffer = new byte[1024];
? ? ? ? ? ? DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
? ? ? ? ? ? socket.receive(packet);//堵塞接收
? ? ? ? ? ? //3.處理數(shù)據(jù)
? ? ? ? ? ? byte[] target = packet.getData();
? ? ? ? ? ? int len=0;
? ? ? ? ? ? if (target.length!=0){
? ? ? ? ? ? ? ? for (int i=0;i<target.length;i++){
? ? ? ? ? ? ? ? ? ? if (target[i]=='\0'){
? ? ? ? ? ? ? ? ? ? ? ? len=i;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? //4.輸出數(shù)據(jù)
? ? ? ? ? ? System.out.println("from:"+packet.getAddress());
? ? ? ? ? ? System.out.println(new String(target,0,len));
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }finally {
? ? ? ? ? ? if (socket!=null){
? ? ? ? ? ? ? ? socket.close();
? ? ? ? ? ? }
? ? ? ? }發(fā)送端:
//1.建立連接
DatagramSocket socket = null;
//2.獲得連接對象
//獲取對方的IP和端口號進行連接
?InetAddress Ip = null;
?int port = 9999;
//4.創(chuàng)建數(shù)據(jù)包
? ? ? ? String msg = "你好";
? ? ? ? DatagramPacket packet = null;
? ? ? ? try {
? ? ? ? ? ? socket = new DatagramSocket();
? ? ? ? ? ? Ip = InetAddress.getByName("localhost");
? ? ? ? ? ? //數(shù)據(jù),數(shù)據(jù)的長度起始,發(fā)送的地址
? ? ? ? ? ? packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,Ip,port);
? ? ? ? ? ? //5.發(fā)送包
? ? ? ? ? ? socket.send(packet);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }finally {
? ? ? ? ? ? //6.關(guān)閉資源
? ? ? ? ? ? if (socket != null){
? ? ? ? ? ? ? ? socket.close();
? ? ? ? ? ? }
? ? ? ? }二、多線程實現(xiàn)UDP在線聊天
1.創(chuàng)鍵服務器端
package chat;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
public class ServerThread implements Runnable{
? ? private final String theOther;//對方的姓名
? ? private final int selfPort;//自己開放的的端口號
? ? private DatagramSocket socket;
? ? public ServerThread(int selfPort,String theOther){//構(gòu)造器
? ? ? ? this.selfPort = selfPort;
? ? ? ? this.theOther = theOther;
? ? ? ? try {
? ? ? ? ? ? //開啟服務器
? ? ? ? ? ? socket = new DatagramSocket(selfPort);
? ? ? ? } catch (SocketException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? public void run() {
? ? ? ? //接收數(shù)據(jù)
? ? ? ? byte[] container;
? ? ? ? DatagramPacket packet;//包
? ? ? ? byte[] date;
? ? ? ? String receiveMsg = "";//信號燈
? ? ? ? int len = 0;
? ? ? ? try {
? ? ? ? ? ? while (!receiveMsg.equals("bye")){//如果對方說:bye,則退出聊天
? ? ? ? ? ? ? ? container = new byte[1024];
? ? ? ? ? ? ? ? packet = new DatagramPacket(container,0,container.length);
? ? ? ? ? ? ? ? socket.receive(packet);//接收數(shù)據(jù)包
? ? ? ? ? ? ? ? date =packet.getData();//獲取數(shù)據(jù)
? ? ? ? ? ? ? ? //處理數(shù)據(jù)
? ? ? ? ? ? ? ? for (int i = 0; i < date.length; i++) {
? ? ? ? ? ? ? ? ? ? if (date[i]=='\0'){
? ? ? ? ? ? ? ? ? ? ? ? len = i;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //將收到的數(shù)據(jù)轉(zhuǎn)換為字符串
? ? ? ? ? ? ? ? receiveMsg = new String(date,0, len, StandardCharsets.UTF_8);
? ? ? ? ? ? ? ? System.out.println(theOther+":"+receiveMsg);
? ? ? ? ? ? }
// ? ? ? ? ? ? ?保存聊天記錄(擴展內(nèi)容)
// ? ? ? ? ? ? ?FileOutputStream out = new FileOutputStream(new File(theOther+"的聊天記錄.txt"));
// ? ? ? ? ? ? ?out.write(receiveMsg.getBytes(StandardCharsets.UTF_8));
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }finally {
? ? ? ? ? ? //關(guān)閉服務器
? ? ? ? ? ? if (socket != null){
? ? ? ? ? ? ? ? socket.close();
? ? ? ? ? ? }
? ? ? ? }
? ? }
}2.建立客戶端
package chat;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;
public class ClientThread implements Runnable{
? ? ?private DatagramSocket socket = null;
? ? ?private BufferedReader bufferedReader= null;//緩沖流
? ? ?private final String toIp;//對方的IP
? ? ?private final int toPort;//對方的端口號
? ? public ClientThread(String toIp, int toPort) {
? ? ? ? this.toIp = toIp;
? ? ? ? this.toPort = toPort;
? ? ? ? try {
? ? ? ? ? ? socket = new DatagramSocket();
? ? ? ? ? ? bufferedReader = new BufferedReader(new InputStreamReader(System.in));//獲取鍵盤輸入
? ? ? ? } catch (SocketException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? public void run() {
? ? ? ? String SendMsg = "";//發(fā)視頻美好的消息
? ? ? ? byte[] date;
? ? ? ? DatagramPacket packet;
? ? ? ? try {
? ? ? ? while(!SendMsg.equals("bye")) {//自己發(fā)送‘bye'時關(guān)閉發(fā)送端
? ? ? ? ? ? SendMsg = bufferedReader.readLine();//讀取鍵盤輸入內(nèi)容
? ? ? ? ? ? date = SendMsg.getBytes(StandardCharsets.UTF_8);//字符串轉(zhuǎn)換為字節(jié)進行傳輸
? ? ? ? ? ? packet = new DatagramPacket(date,0,date.length,new InetSocketAddress(toIp,toPort));
? ? ? ? ? ? socket.send(packet);//發(fā)送數(shù)據(jù)
? ? ? ? }
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? }finally {
? ? ? ? ? ? //關(guān)閉數(shù)據(jù)流
? ? ? ? ? ? if (bufferedReader!=null){
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? bufferedReader.close();
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if(socket!=null){
? ? ? ? ? ? ? ? socket.close();
? ? ? ? ? ? }
? ? ? ? }
? ? }
}3.用戶使用:
用戶1:
package chat;
public class User01 {
? ? public static void main(String[] args) {
? ? ? ? System.out.println("小明的聊天室?。。?);
? ? ? ? new Thread(new ServerThread(9000,"小紅")).start();//開啟接收
? ? ? ? new Thread(new ClientThread("localhost",9001)).start();//開啟發(fā)送
? ? }
}用戶2:
package chat;
public class User02 {
? ? public static void main(String[] args) {
? ? ? ? System.out.println("小紅的聊天室?。。?);
? ? ? ? new Thread(new ServerThread(9001,"小明")).start();
? ? ? ? new Thread(new ClientThread("localhost",9000)).start();
? ? }
}多人聊天思路:
用戶—>公共服務器接收端打包數(shù)據(jù)–>服務器發(fā)送端發(fā)送給各個用戶—>用戶
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot使用Hutool的JschUtil及下載安裝步驟
這篇文章主要為大家介紹了springboot使用Hutool的JschUtil的方法及下載安裝詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
Java 數(shù)組復制clone方法實現(xiàn)詳解
這篇文章主要介紹了Java 數(shù)組復制clone方法實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
SpringBoot開發(fā)項目,引入JPA找不到findOne方法的解決
這篇文章主要介紹了SpringBoot開發(fā)項目,引入JPA找不到findOne方法的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Spring中利用SchedulingConfigurer實現(xiàn)動態(tài)定時任務配置的示例
定時任務是一項至關(guān)重要的功能,它們使得我們能夠按照預定的時間執(zhí)行特定的任務,本文主要介紹了Spring中利用SchedulingConfigurer實現(xiàn)動態(tài)定時任務配置的示例,感興趣的可以了解一下2024-05-05
SpringBoot集成echarts實現(xiàn)k線圖功能
ECharts是一款基于JavaScript的數(shù)據(jù)可視化圖表庫,提供直觀,生動,可交互,可個性化定制的數(shù)據(jù)可視化圖表,本文給大家介紹了SpringBoot集成echarts實現(xiàn)k線圖功能,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下2024-07-07

