java实现简易局域网聊天功能

时间:2021-05-02

本文实例为大家分享了java使用udp模式编写聊天程序的具体代码,供大家参考,具体内容如下

java代码:

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 import java.net.*; import java.io.*; class demo { public static void main(string[] args) throws exception { datagramsocket sendsocket = new datagramsocket(9998); //发送端 datagramsocket recesocket = new datagramsocket(9999); //接收端 new thread(new msgsend(sendsocket)).start(); //发送线程 new thread(new msgrece(recesocket)).start(); //接受线程 } } class msgsend implements runnable //发送 { private datagramsocket dsock; public msgsend(datagramsocket dsock) { this.dsock= dsock; } public void run() { bufferedreader bufr = new bufferedreader(new inputstreamreader(system.in)); string linestr = null; try { while(true) { linestr = bufr.readline(); if(linestr!=null) { if(linestr.equals("over886")) { break; } else { byte[] databuf = linestr.getbytes(); datagrampacket datapack = //数据打包 new datagrampacket( databuf, databuf.length, inetaddress.getbyname("192.168.1.255"), //广播 9999 //目标端口 ); dsock.send(datapack); } } } bufr.close(); dsock.close(); } catch(exception e) { throw new runtimeexception("发送失败!"); } } } class msgrece implements runnable //接收 { private datagramsocket dsock; public msgrece(datagramsocket dsock) { this.dsock= dsock; } public void run() { try { while(true) { byte[] databuf = new byte[1024]; datagrampacket datapack = new datagrampacket(databuf,databuf.length); dsock.receive(datapack); //将获取的数据保存到指定的数据包 string ip = datapack.getaddress().gethostaddress(); string data = new string(datapack.getdata(),0,datapack.getlength()); int port = datapack.getport(); system.out.println(); system.out.println("来自ip为 "+ip+" <对方端口>: "+port+" 的消息"); system.out.println(data); } } catch(exception e) { throw new runtimeexception("接受失败!"); } finally { dsock.close(); } } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://xouou.iteye.com/blog/1356391

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章