先说一下
写的确实比较一般,别喷
为什么呢,疫情原因,学校提前两周期末考试,时间也不太充足,将就一下
服务器代码:
package xcvcvcx;import java.io.bufferedreader;import java.io.bufferedwriter;import java.io.ioexception;import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.io.outputstreamwriter;import java.net.rversocket;import java.net.socket;import java.nio.chart.standardcharts;import java.util.hashmap;import java.util.map;public class rver { static int index = 0; static bufferedwriter[] urwrite = new bufferedwriter[100]; static bufferedreader[] urread = new bufferedreader[100]; static socket[] ursocket = new socket[100]; static string[] urid = new string[100]; static string[] urname = new string[100]; public static void main(string[] args) throws ioexception { rversocket ss = new rversocket(6666); // 监听指定端口 system.out.println("rver is running..."); index = 0; for (;;) { socket sock = ss.accept(); string idd = sock.getremotesocketaddress().tostring(); system.out.println("connected from " + sock.getremotesocketaddress()); ursocket[index] = sock; thread t = new handler(sock); ((handler) t).urid = idd; urid[index]=((handler) t).urid =idd; t.start(); } }}class handler extends thread { socket sock; bufferedwriter writer; bufferedreader reader; string urname; string urid; public handler(socket sock) { this.sock = sock; } public void synmessage(map<string,string> message) throws ioexception { bufferedwriter writer; bufferedwriter[] ur =rver.urwrite; int isall =1; string dis = "a"; if ( message.get("messageclass").tostring().equals("normally") ){ dis = message.get("distination"); system.out.println(dis); system.out.println(); if (dis.equals("all") == fal){ system.out.println("no isall"); isall= 0; } } int len = rver.index; for(int i =0; i< len;i++) { if (rver.urwrite[i] == null){ continue; } system.out.println("vf"); if (isall == 0){ // 专门的消息 if (rver.urname[i].equals(dis)){ message.put( "distinationid",rver.urid[i] ); writer = ur[i]; writer.write(message.tostring() + "\n"); system.out.print("专门消息发送成功"); writer.flush(); return; } continue; } message.put( "distinationid",rver.urid[i] ); if (rver.urwrite[i] == null){ continue; } if ( rver.urid[i].equals(this.urid) == fal) { writer = ur[i]; writer.write(message.tostring() + "\n"); system.out.print("进来了"); writer.flush(); }el { writer = ur[i]; writer.write(message.tostring() + "\n"); system.out.print("进来了"); writer.flush(); } } } public void synurlist(map<string,string> message,string id){ bufferedwriter writer; bufferedwriter[] ur =rver.urwrite; // 封装 用户列表 // 规定用户名不可以有空格 int len = rver.index; string urlis = "here"; for (int i = 0; i< len ; i++) { system.out.println(urlis); if (rver.urwrite[i]!=null){ if (message.get("urid").equals(rver.urid[i])){ continue; }el { if (rver.urname[i] ==null){ continue; } urlis = urlis + " " + rver.urname[i]; } } } message.put( "distinationid",id); message.put( "urlist",urlis); message.put("messageclass","synurlist"); for(int i =0; i< len;i++) { if (rver.urwrite[i] == null){ continue; } if ( rver.urid[i].equals(id)) { writer = ur[i]; try { writer.write(message.tostring() + "\n"); writer.flush(); return; } catch (ioexception e) { e.printstacktrace(); } } } }大数据专业 @override public void run() { try (inputstream input = this.sock.getinputstream()) { try (outputstream output = this.sock.getoutputstream()) { handle(input, output); } } catch (exception e) { try { this.sock.clo(); } catch (ioexception ioe) { } system.out.println("client disconnected."); } } private void handle(inputstream input, outputstream output) throws ioexception { bufferedwriter writer = new bufferedwriter(new outputstreamwriter(output, standardcharts.utf_8)); bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharts.utf_8)); this.writer = writer; this.reader = reader; int inde = rver.index; rver.index++; rver.urread[inde] = reader; rver.urwrite[inde] = writer; map<string,string> message= new hashmap<string, string>(); message.put("messageclass", "synid");// 普通 消息 message.put( "urid",urid ); message.put( "urindex",string.valueof(inde) ); string to=message.tostring(); writer.write(to+'\n'); writer.flush(); for (;;) { string s = reader.readline(); if (s == null){ continue; }// system.out.print(s);// synmessages(s); map<string, string> mess= client.mapstringtomap(s);//// system.out.print(s); if(mess.get("messageclass").tostring().equals("normally")) { system.out.print("irieowmxn"); synmessage(mess); continue; }el if (mess.get("messageclass").tostring().equals("synurname")){ system.out.println("now synur"); string id = mess.get("urid"); system.out.println(mess.tostring()); urname = mess.get("ur"); int index = integer.parint( mess.get("urindex") ); rver.urname[index] = urname; // 同步 在线用户 map<string,string> synur= new hashmap<string, string>(); synur.put("messageclass", "addur");// 普通 消息 synur.put( "urname",urname ); synmessage(synur); // 同步所以已在线用户, 有新用户 登录 // 其实 我们还需要 回复 该用户, 现在有哪些在线 以便于 后来登录的人 用户列表 无法更新 synurlist(message,id); continue; }el if ( mess.get("messageclass").tostring().equals("urclo") ){ map<string,string> synur= new hashmap<string, string>(); synur.put("messageclass", "urclo");// 普通 消息 synur.put( "urname",urname ); synmessage(synur); int iin = integer.parint(mess.get("urindex")); rver.urwrite[iin] = null; } if (s.equals("bye")) { writer.write("bye\n"); writer.flush(); break; } } }}
客户端:
package xcvcvcx;import java.awt.borderlayout;import java.awt.flowlayout;import java.awt.gridlayout;import java.awt.event.actionevent;import java.awt.event.actionlistener;import java.awt.event.itemevent;import java.awt.event.itemlistener;import java.io.bufferedreader;import java.io.bufferedwriter;import java.io.ioexception;import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.io.outputstreamwriter;import java.net.socket;import java.net.socketaddress;import java.nio.chart.standardcharts;import java.text.simpledateformat;import java.util.date;import java.util.hashmap;import java.util.map;import java.util.scanner;import javax.swing.jbutton;import javax.swing.jcombobox;import javax.swing.jframe;import javax.swing.jlabel;import javax.swing.jpanel;import javax.swing.jscrollpane;import javax.swing.jtextarea;import javax.swing.jtextfield;import javax.swing.windowconstants;public class client extends jframe implements actionlistener ,itemlistener {private string currentt_urname = null;//各种组件jlabel jlabelverip,jlabelverport,jlabelreceivedata,jlabelntdata;jtextfield jtextfieldverip,jtextfieldverport,jtextfieldntdata;jbutton jbuttontupver,jbuttonclonetwork,jbuttonnt;jtextarea jtextareareceivedata;jbutton jbuttonexit;// 当前在线用户部分jlabel jlabelonlinur;jcombobox jcomboboxonlineur;//组件完毕bufferedreader reader;bufferedwriter writer;// 存储用户信息jlabel jlabelurname;jtextfield jtextfieldurname;string urid ;socket sock;int urindex;// 服务连接相关string rveraddress ="192.168.43.240" ; // 可以自己设置int port = 6666;public client(){init();}public void init(){//初始化jlabelreceivedata=new jlabel("接受数据:");jlabelntdata=new jlabel("发送数据:");jlabelverip=new jlabel("服务器ip");jlabelverport=new jlabel("服务器端口");jtextfieldntdata=new jtextfield(15);jtextfieldverip=new jtextfield(7);jtextfieldverport=new jtextfield(7);jbuttonclonetwork=new jbutton("关闭服务");jbuttonnt=new jbutton("发送");jbuttontupver=new jbutton("开启服务");jtextareareceivedata=new jtextarea(20,15);jscrollpane scroller = new jscrollpane(jtextareareceivedata);scroller.tverticalscrollbarpolicy(jscrollpane.vertical_scrollbar_always);jtextareareceivedata.twrapstyleword(true);//设置单词在一行不足容纳时换行jtextareareceivedata.tlinewrap(true);//设置文本编辑区自动换行默认为true,即会"自动换行"//this.add(editarea,borderlayout.center);//向窗口添加文本编辑区jbuttonexit = new jbutton("退出");//组件初始化// 存储 用户信息jlabelurname = new jlabel("用户名");jtextfieldurname = new jtextfield(10);jlabelonlinur = new jlabel("在线用户");jcomboboxonlineur = new jcombobox();jcomboboxonlineur.additemlistener(this::itemstatechanged);jcomboboxonlineur.additem("lf");jpanel panel1=new jpanel();panel1.tlayout(new flowlayout());panel1.add(jlabelverip);panel1.add(jtextfieldverip);panel1.add(jlabelverport);panel1.add(jtextfieldverport);panel1.add(jbuttontupver);panel1.add(jbuttonclonetwork);jpanel panel2=new jpanel();panel2.add(jlabelreceivedata);jpanel jpanelurinfor = new jpanel();jpanelurinfor.tlayout(new flowlayout());jpanelurinfor.add(jlabelurname);jpanelurinfor.add((jtextfieldurname));jpanelurinfor.add(jlabelonlinur);jpanelurinfor.add(jcomboboxonlineur);jpanel jpanel1=new jpanel();jpanel1.tlayout(new gridlayout(3,1));jpanel1.add(panel1);jpanel1.add(jpanelurinfor);jpanel1.add(panel2);jpanel panel3=new jpanel();panel3.tlayout(new flowlayout());panel3.add(jlabelntdata);jpanel panel4=new jpanel();panel4.tlayout(new flowlayout());panel4.add(jtextfieldntdata);panel4.add(jbuttonnt);panel4.add(jbuttonexit);jpanel jpanel2=new jpanel();jpanel2.tlayout(new gridlayout(2,1));jpanel2.add(panel3);jpanel2.add(panel4);jpanel jpanel=new jpanel();jpanel.tlayout(new borderlayout());jpanel.add(jpanel1,borderlayout.north);jpanel.add(scroller,borderlayout.center);jpanel.add(jpanel2,borderlayout.south);//完成组件组合jbuttonnt.addactionlistener(this);jbuttontupver.addactionlistener(this);jbuttonclonetwork.addactionlistener(this);jbuttonexit.addactionlistener(this);tsize(600,400);tdefaultclooperation(windowconstants.exit_on_clo);add(jpanel);tvisible(true);//显示jbuttonclonetwork.tenabled(fal);jtextfieldverip.ttext(rveraddress);jtextfieldverport.ttext(string.valueof(port));jtextareareceivedata.append("本程序只用于简单演示,\n若要修改服务器地址或端口,请修改指定代码,暂不支持手动指定\n\n\n");// 连接服务器try {socket sock = new socket(rveraddress, port);this.sock = sock;try (inputstream input = sock.getinputstream()) {try (outputstream output = sock.getoutputstream()) {bufferedwriter writer = new bufferedwriter(new outputstreamwriter(output, standardch10一14young videoarts.utf_8));bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharts.utf_8));socketaddress id = sock.getremotesocketaddress();urid = sock.getremotesocketaddress().tostring();this.writer =writer;this.reader = reader;while(true)for (; ; ) {string resp = reader.readline();while (resp == null) {resp = reader.readline();}system.out.println("<<< " + resp);map<string, string> message = mapstringtomap(resp);if (message.get("messageclass").equals("synid")) {system.out.println(urid);urid = message.get("urid");system.out.println(message.keyt());system.out.println(urid);// 更新 服务器 接口 处的 内容jtextareareceivedata.append("已为您成功分配id 请填写用户名,并开启服务");jtextareareceivedata.append(resp);jtextareareceivedata.append("\n");urindex = integer.parint(message.get("urindex"));continue;} el if (message.get("messageclass").equals("normally")) {resp = message.tostring();system.out.print("748328");// 正常消息string showmess = "";string dist = message.get("distination");if (dist.equals("all")){showmess = showmess.concat("消息类型:全体消息" + '\n');}el {showmess = showmess.concat("消息类型:私发消息" + '\n');}showmess = showmess.concat("消息时间: " + message.get("time") + '\n');showmess = showmess.concat("消息内容: " + message.get("content") + '\n');showmess = showmess.concat("消息来源: " + message.get("ur") + '\n');jtextareareceivedata.append(showmess);jtextareareceivedata.append("\n\n");} el if (message.get("messageclass").equals("addur")) {if (currentt_urname ==null){continue;}system.out.println(message.tostring());string newname = message.get("urname");if (newname.equals(currentt_urname) == fal) {jcomboboxonlineur.additem(newname);jtextareareceivedata.append("有新用户上线了:他是: " + newname + "\n\n" );}} el if (message.get("messageclass").tostring().equals("urclo")) {string name = message.get("urname");system.out.println("现在 删除 ur: " + name);jtextareareceivedata.append("有用户下线了:他是: " + name + "\n\n" );jcomboboxonlineur.removeitem(name);}el if( message.get("messageclass").tostring().equals("synurlist") ){string lis = message.get("urlist");string[] urlist = lis.split(" ");int i;for(i=1; i<urlist.length;i++) {jcomboboxonlineur.additem(urlist[i]);}}}}}} catch (ioexception e) {e.printstacktrace();}}public static map<string,string> mapstringtomap(string str){str=str.substring(1, str.length()-1);system.out.println("ishere dk->" + str);string[] strs=str.split(",");map<string,string> map = new hashmap<string, s增值税免税项目tring>();for (string string : strs) {string key=string.split("=")[0];string value=string.split("=")[1];value = value.trim();key = key.trim();map.put(key, value);}return map;}public static void main(string[] args) throws ioexception {client a = new client();}private static void handle(inputstream input, outputstream output) throws ioexception {bufferedwriter writer = new bufferedwriter(new outputstreamwriter(output, standardcharts.utf_8));bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharts.utf_8));scanner scanner = new scanner(system.in);system.out.println("[rver] " + reader.readl高档粤菜ine());for (;;) {system.out.print(">>> "); // 打印提示string s = scanner.nextline(); // 读取一行输入writer.write(s);writer.newline();writer.flush();string resp = reader.readline();system.out.println("<<< " + resp);if (resp.equals("bye")) {break;}}}void update() throws ioexception {for (;;) {system.out.print("lkdfvmndfjk");string resp = reader.readline();system.out.println("<<< " + resp);jtextareareceivedata.append(resp);if (resp.equals("bye")) {break;}}}static string time (){simpledateformat df = new simpledateformat("yyyy-mm-dd hh:mm:ss");//设置日期格式return df.format( new date() ).tostring();}@overridepublic void actionperformed(actionevent e) {if (e.getsource()==jbuttonnt){if (jtextfieldntdata.gettext() == "") {jtextareareceivedata.append("发送不可为空"+"\n");}el {this.currentt_urname = jtextfieldurname.gettext().tostring();map<string,string> message= new hashmap<string, string>();message.put("messageclass", "normally");// 普通 消息message.put("ur",currentt_urname);message.put( "urid",urid );string to=jtextfieldntdata.gettext();message.put("content",to);message.put("time",time());string distina = jcomboboxonlineur.getlecteditem().tostring();if (distina.equals("lf")){// 发给所有人system.out.println("查看");message.put("distination","all");}el {// 发给某人message.put("distination",distina);}string ans = message.tostring();to = ans;try {writer.write(to+"\n");writer.flush();}catch (exception ee){system.out.println(ee.tostring());jtextareareceivedata.append("发送失败"+"\n");}}}el if (e.getsource() == jbuttonclonetwork){try {sock.clo();} catch (ioexception e1) {e1.printstacktrace();}}el if(e.getsource() == jbuttontupver){string name = jte关于运动会的新闻xtfieldurname.gettext();if (name.equals("")){jtextareareceivedata.append("用户名不可为空");// 不可为空 提示return;}currentt_urname = name;map<string,string> message= new hashmap<string, string>();message.put("messageclass", "synurname");// 普通 消息message.put("ur",currentt_urname);message.put( "urid",urid );message.put( "urindex",string.valueof(urindex) );try {writer.write(message.tostring()+"\n");writer.flush();jbuttonclonetwork.tenabled(true);jbuttontupver.tenabled(fal);} catch (ioexception e1) {e1.printstacktrace();}// 同步 用户名}el if (e.getsource()== jbuttonexit){// 关闭按钮map<string,string> message= new hashmap<string, string>();message.put("messageclass", "urclo");// 普通 消息message.put("ur",currentt_urname);message.put( "urid",urid );message.put( "urindex",string.valueof(urindex) );try {writer.write(message.tostring()+"\n");writer.flush();system.out.println(message.tostring());} catch (ioexception e1) {e1.printstacktrace();}// 发送下线消息jcomboboxonlineur.removeallitems();}}@overridepublic void itemstatechanged(itemevent e) {}}
里面的ip地址 我写的是我自己的 想改的可以自己改
以上就是基于java实现简易的局域网对话系统的详细内容,更多关于java局域网对话系统的资料请关注www.887551.com其它相关文章!
本文发布于:2023-04-04 04:11:48,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/065555a89db0291d86b40c359dabfe75.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:基于Java实现简易的局域网对话系统.doc
本文 PDF 下载地址:基于Java实现简易的局域网对话系统.pdf
留言与评论(共有 0 条评论) |