基于Java实现简易的局域网对话系统
程序员文章站
2022-06-18 09:30:09
先说一下写的确实比较一般,别喷为什么呢,疫情原因,学校提前两周期末考试,时间也不太充足,将就一下服务器代码:package xcvcvcx;import java.io.bufferedreader;...
先说一下
写的确实比较一般,别喷
为什么呢,疫情原因,学校提前两周期末考试,时间也不太充足,将就一下
服务器代码:
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.serversocket; import java.net.socket; import java.nio.charset.standardcharsets; import java.util.hashmap; import java.util.map; public class server { static int index = 0; static bufferedwriter[] userwrite = new bufferedwriter[100]; static bufferedreader[] userread = new bufferedreader[100]; static socket[] usersocket = new socket[100]; static string[] userid = new string[100]; static string[] username = new string[100]; public static void main(string[] args) throws ioexception { serversocket ss = new serversocket(6666); // 监听指定端口 system.out.println("server is running..."); index = 0; for (;;) { socket sock = ss.accept(); string idd = sock.getremotesocketaddress().tostring(); system.out.println("connected from " + sock.getremotesocketaddress()); usersocket[index] = sock; thread t = new handler(sock); ((handler) t).userid = idd; userid[index]=((handler) t).userid =idd; t.start(); } } } class handler extends thread { socket sock; bufferedwriter writer; bufferedreader reader; string username; string userid; public handler(socket sock) { this.sock = sock; } public void synmessage(map<string,string> message) throws ioexception { bufferedwriter writer; bufferedwriter[] user =server.userwrite; 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") == false){ system.out.println("no isall"); isall= 0; } } int len = server.index; for(int i =0; i< len;i++) { if (server.userwrite[i] == null){ continue; } system.out.println("vf"); if (isall == 0){ // 专门的消息 if (server.username[i].equals(dis)){ message.put( "distinationid",server.userid[i] ); writer = user[i]; writer.write(message.tostring() + "\n"); system.out.print("专门消息发送成功"); writer.flush(); return; } continue; } message.put( "distinationid",server.userid[i] ); if (server.userwrite[i] == null){ continue; } if ( server.userid[i].equals(this.userid) == false) { writer = user[i]; writer.write(message.tostring() + "\n"); system.out.print("进来了"); writer.flush(); }else { writer = user[i]; writer.write(message.tostring() + "\n"); system.out.print("进来了"); writer.flush(); } } } public void synuserlist(map<string,string> message,string id){ bufferedwriter writer; bufferedwriter[] user =server.userwrite; // 封装 用户列表 // 规定用户名不可以有空格 int len = server.index; string userlis = "here"; for (int i = 0; i< len ; i++) { system.out.println(userlis); if (server.userwrite[i]!=null){ if (message.get("userid").equals(server.userid[i])){ continue; }else { if (server.username[i] ==null){ continue; } userlis = userlis + " " + server.username[i]; } } } message.put( "distinationid",id); message.put( "userlist",userlis); message.put("messageclass","synuserlist"); for(int i =0; i< len;i++) { if (server.userwrite[i] == null){ continue; } if ( server.userid[i].equals(id)) { writer = user[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.close(); } catch (ioexception ioe) { } system.out.println("client disconnected."); } } private void handle(inputstream input, outputstream output) throws ioexception { bufferedwriter writer = new bufferedwriter(new outputstreamwriter(output, standardcharsets.utf_8)); bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharsets.utf_8)); this.writer = writer; this.reader = reader; int inde = server.index; server.index++; server.userread[inde] = reader; server.userwrite[inde] = writer; map<string,string> message= new hashmap<string, string>(); message.put("messageclass", "synid");// 普通 消息 message.put( "userid",userid ); message.put( "userindex",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; }else if (mess.get("messageclass").tostring().equals("synusername")){ system.out.println("now synuser"); string id = mess.get("userid"); system.out.println(mess.tostring()); username = mess.get("user"); int index = integer.parseint( mess.get("userindex") ); server.username[index] = username; // 同步 在线用户 map<string,string> synuser= new hashmap<string, string>(); synuser.put("messageclass", "adduser");// 普通 消息 synuser.put( "username",username ); synmessage(synuser); // 同步所以已在线用户, 有新用户 登录 // 其实 我们还需要 回复 该用户, 现在有哪些在线 以便于 后来登录的人 用户列表 无法更新 synuserlist(message,id); continue; }else if ( mess.get("messageclass").tostring().equals("userclose") ){ map<string,string> synuser= new hashmap<string, string>(); synuser.put("messageclass", "userclose");// 普通 消息 synuser.put( "username",username ); synmessage(synuser); int iin = integer.parseint(mess.get("userindex")); server.userwrite[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.charset.standardcharsets; 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_username = null; //各种组件 jlabel jlabelseverip,jlabelseverport,jlabelreceivedata,jlabelsentdata; jtextfield jtextfieldseverip,jtextfieldseverport,jtextfieldsentdata; jbutton jbuttonsetupsever,jbuttonclosenetwork,jbuttonsent; jtextarea jtextareareceivedata; jbutton jbuttonexit; // 当前在线用户部分 jlabel jlabelonlinuser; jcombobox jcomboboxonlineuser; //组件完毕 bufferedreader reader; bufferedwriter writer; // 存储用户信息 jlabel jlabelusername; jtextfield jtextfieldusername; string userid ; socket sock; int userindex; // 服务连接相关 string serveraddress ="192.168.43.240" ; // 可以自己设置 int port = 6666; public client(){ init(); } public void init(){ //初始化 jlabelreceivedata=new jlabel("接受数据:"); jlabelsentdata=new jlabel("发送数据:"); jlabelseverip=new jlabel("服务器ip"); jlabelseverport=new jlabel("服务器端口"); jtextfieldsentdata=new jtextfield(15); jtextfieldseverip=new jtextfield(7); jtextfieldseverport=new jtextfield(7); jbuttonclosenetwork=new jbutton("关闭服务"); jbuttonsent=new jbutton("发送"); jbuttonsetupsever=new jbutton("开启服务"); jtextareareceivedata=new jtextarea(20,15); jscrollpane scroller = new jscrollpane(jtextareareceivedata); scroller.setverticalscrollbarpolicy(jscrollpane.vertical_scrollbar_always); jtextareareceivedata.setwrapstyleword(true);//设置单词在一行不足容纳时换行 jtextareareceivedata.setlinewrap(true);//设置文本编辑区自动换行默认为true,即会"自动换行" //this.add(editarea,borderlayout.center);//向窗口添加文本编辑区 jbuttonexit = new jbutton("退出"); //组件初始化 // 存储 用户信息 jlabelusername = new jlabel("用户名"); jtextfieldusername = new jtextfield(10); jlabelonlinuser = new jlabel("在线用户"); jcomboboxonlineuser = new jcombobox(); jcomboboxonlineuser.additemlistener(this::itemstatechanged); jcomboboxonlineuser.additem("self"); jpanel panel1=new jpanel(); panel1.setlayout(new flowlayout()); panel1.add(jlabelseverip); panel1.add(jtextfieldseverip); panel1.add(jlabelseverport); panel1.add(jtextfieldseverport); panel1.add(jbuttonsetupsever); panel1.add(jbuttonclosenetwork); jpanel panel2=new jpanel(); panel2.add(jlabelreceivedata); jpanel jpaneluserinfor = new jpanel(); jpaneluserinfor.setlayout(new flowlayout()); jpaneluserinfor.add(jlabelusername); jpaneluserinfor.add((jtextfieldusername)); jpaneluserinfor.add(jlabelonlinuser); jpaneluserinfor.add(jcomboboxonlineuser); jpanel jpanel1=new jpanel(); jpanel1.setlayout(new gridlayout(3,1)); jpanel1.add(panel1); jpanel1.add(jpaneluserinfor); jpanel1.add(panel2); jpanel panel3=new jpanel(); panel3.setlayout(new flowlayout()); panel3.add(jlabelsentdata); jpanel panel4=new jpanel(); panel4.setlayout(new flowlayout()); panel4.add(jtextfieldsentdata); panel4.add(jbuttonsent); panel4.add(jbuttonexit); jpanel jpanel2=new jpanel(); jpanel2.setlayout(new gridlayout(2,1)); jpanel2.add(panel3); jpanel2.add(panel4); jpanel jpanel=new jpanel(); jpanel.setlayout(new borderlayout()); jpanel.add(jpanel1,borderlayout.north); jpanel.add(scroller,borderlayout.center); jpanel.add(jpanel2,borderlayout.south); //完成组件组合 jbuttonsent.addactionlistener(this); jbuttonsetupsever.addactionlistener(this); jbuttonclosenetwork.addactionlistener(this); jbuttonexit.addactionlistener(this); setsize(600,400); setdefaultcloseoperation(windowconstants.exit_on_close); add(jpanel); setvisible(true); //显示 jbuttonclosenetwork.setenabled(false); jtextfieldseverip.settext(serveraddress); jtextfieldseverport.settext(string.valueof(port)); jtextareareceivedata.append("本程序只用于简单演示,\n若要修改服务器地址或端口,请修改指定代码,暂不支持手动指定\n\n\n"); // 连接服务器 try { socket sock = new socket(serveraddress, port); this.sock = sock; try (inputstream input = sock.getinputstream()) { try (outputstream output = sock.getoutputstream()) { bufferedwriter writer = new bufferedwriter(new outputstreamwriter(output, standardcharsets.utf_8)); bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharsets.utf_8)); socketaddress id = sock.getremotesocketaddress(); userid = 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(userid); userid = message.get("userid"); system.out.println(message.keyset()); system.out.println(userid); // 更新 服务器 接口 处的 内容 jtextareareceivedata.append("已为您成功分配id 请填写用户名,并开启服务"); jtextareareceivedata.append(resp); jtextareareceivedata.append("\n"); userindex = integer.parseint(message.get("userindex")); continue; } else 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'); }else { showmess = showmess.concat("消息类型:私发消息" + '\n'); } showmess = showmess.concat("消息时间: " + message.get("time") + '\n'); showmess = showmess.concat("消息内容: " + message.get("content") + '\n'); showmess = showmess.concat("消息来源: " + message.get("user") + '\n'); jtextareareceivedata.append(showmess); jtextareareceivedata.append("\n\n"); } else if (message.get("messageclass").equals("adduser")) { if (currentt_username ==null){ continue; } system.out.println(message.tostring()); string newname = message.get("username"); if (newname.equals(currentt_username) == false) { jcomboboxonlineuser.additem(newname); jtextareareceivedata.append("有新用户上线了:他是: " + newname + "\n\n" ); } } else if (message.get("messageclass").tostring().equals("userclose")) { string name = message.get("username"); system.out.println("现在 删除 user: " + name); jtextareareceivedata.append("有用户下线了:他是: " + name + "\n\n" ); jcomboboxonlineuser.removeitem(name); }else if( message.get("messageclass").tostring().equals("synuserlist") ){ string lis = message.get("userlist"); string[] userlist = lis.split(" "); int i; for(i=1; i<userlist.length;i++) { jcomboboxonlineuser.additem(userlist[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, string>(); 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, standardcharsets.utf_8)); bufferedreader reader = new bufferedreader(new inputstreamreader(input, standardcharsets.utf_8)); scanner scanner = new scanner(system.in); system.out.println("[server] " + reader.readline()); 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(); } @override public void actionperformed(actionevent e) { if (e.getsource()==jbuttonsent){ if (jtextfieldsentdata.gettext() == "") { jtextareareceivedata.append("发送不可为空"+"\n"); }else { this.currentt_username = jtextfieldusername.gettext().tostring(); map<string,string> message= new hashmap<string, string>(); message.put("messageclass", "normally");// 普通 消息 message.put("user",currentt_username); message.put( "userid",userid ); string to=jtextfieldsentdata.gettext(); message.put("content",to); message.put("time",time()); string distina = jcomboboxonlineuser.getselecteditem().tostring(); if (distina.equals("self")){ // 发给所有人 system.out.println("查看"); message.put("distination","all"); }else { // 发给某人 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"); } } }else if (e.getsource() == jbuttonclosenetwork){ try { sock.close(); } catch (ioexception e1) { e1.printstacktrace(); } }else if(e.getsource() == jbuttonsetupsever){ string name = jtextfieldusername.gettext(); if (name.equals("")){ jtextareareceivedata.append("用户名不可为空"); // 不可为空 提示 return; } currentt_username = name; map<string,string> message= new hashmap<string, string>(); message.put("messageclass", "synusername");// 普通 消息 message.put("user",currentt_username); message.put( "userid",userid ); message.put( "userindex",string.valueof(userindex) ); try { writer.write(message.tostring()+"\n"); writer.flush(); jbuttonclosenetwork.setenabled(true); jbuttonsetupsever.setenabled(false); } catch (ioexception e1) { e1.printstacktrace(); } // 同步 用户名 }else if (e.getsource()== jbuttonexit){ // 关闭按钮 map<string,string> message= new hashmap<string, string>(); message.put("messageclass", "userclose");// 普通 消息 message.put("user",currentt_username); message.put( "userid",userid ); message.put( "userindex",string.valueof(userindex) ); try { writer.write(message.tostring()+"\n"); writer.flush(); system.out.println(message.tostring()); } catch (ioexception e1) { e1.printstacktrace(); }// 发送下线消息 jcomboboxonlineuser.removeallitems(); } } @override public void itemstatechanged(itemevent e) { } }
里面的ip地址 我写的是我自己的 想改的可以自己改
以上就是基于java实现简易的局域网对话系统的详细内容,更多关于java局域网对话系统的资料请关注其它相关文章!