您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“java控制臺(tái)如何實(shí)現(xiàn)聊天程序”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“java控制臺(tái)如何實(shí)現(xiàn)聊天程序”吧!
本文實(shí)例為大家分享了java控制臺(tái)實(shí)現(xiàn)聊天程序的具體代碼,供大家參考,具體內(nèi)容如下
發(fā)送端
package ip.chat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class TalkSend implements Runnable{ DatagramSocket socket = null; BufferedReader reader = null; private int formIP; private String toIP; private int toPort; public TalkSend(int formIP, String toIP, int toPort) { this.formIP = formIP; this.toIP = toIP; this.toPort = toPort; try { socket = new DatagramSocket(); reader = new BufferedReader(new InputStreamReader(System.in)); }catch (Exception e){ e.printStackTrace(); } } @Override public void run() { while (true){ try { String data = reader.readLine(); byte[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort)); socket.send(packet); if (data.equals("bye")){ break; } }catch (Exception e){ e.printStackTrace(); } } //關(guān)閉 socket.close(); } }
服務(wù)端
package ip.chat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TalkReceive implements Runnable{ DatagramSocket socket = null; private int port; //設(shè)置消息來源 private String msgFrom; public TalkReceive(int port ,String msgFrom) { this.port = port; this.msgFrom = msgFrom; try { socket = new DatagramSocket(port); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while(true){ try { //準(zhǔn)備接收包裹 byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet);//接收包裹 //斷開連接 byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length); System.out.println(msgFrom+":"+receiveData); if (receiveData.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
學(xué)生端代碼
package ip.chat; public class TalkStudent { public static void main(String[] args) { //開啟兩個(gè)線程 new Thread(new TalkSend(7777,"localhost",9999)).start(); new Thread(new TalkReceive(8888,"老師")).start(); } }
教師端代碼
package ip.chat; public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkSend(5555,"localhost",8888)).start(); new Thread(new TalkReceive(9999,"學(xué)生")).start(); } }
到此,相信大家對(duì)“java控制臺(tái)如何實(shí)現(xiàn)聊天程序”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。