java控制台实现聊天程序
程序员文章站
2022-07-04 12:43:40
本文实例为大家分享了java控制台实现聊天程序的具体代码,供大家参考,具体内容如下发送端package ip.chat;import java.io.bufferedreader;import jav...
本文实例为大家分享了java控制台实现聊天程序的具体代码,供大家参考,具体内容如下
发送端
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(); } } //关闭 socket.close(); } }
服务端
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; //设置消息来源 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 { //准备接收包裹 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(); } }
学生端代码
package ip.chat; public class talkstudent { public static void main(string[] args) { //开启两个线程 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,"学生")).start(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: java异常级别与捕获的示例代码
下一篇: 晋国弑君现象的发生,背后有哪些原因?