Javase Chat Room
Client:
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.Socket;
Import java.net.SocketException;
Import Java.util.Scanner;
Import Clinet.untils.InputUtil;
Import Configs.configs;
public class Clientdemo {
private static outputstream out;
private static InputStream in;
public static Scanner SC;
public static void Main (string[] args) {try {socket s = new socket ("127.0.0.1", 1008); out = S.getoutputstream (); in = S.getinputstream (); sc = new Scanner (system.in); while (true) {System.out.println ("Please enter the user name you want to register:"); String username = Sc.nextline (); Out.write (Username.getbytes ()); byte[] bys = new byte[1024]; int len = In.read (bys); String msg = new String (bys, 0, Len); if (msg.equals ("yes")) {System.out.println (username + "Login succeeded"); Break } else {System.out.println ("the user already exists, please re-enter the user name"); }} clientthread ct = new Clientthread (in); Ct.start (); Boolean flag =true; while (flag) {System.out.println ("Please select type: 1 private chat, 2 public chat, 3 online people, 4 downline"); Message type Message object: Message content: message type int num = Inpututil.inputinttype (new Scanner (system.in)); Switch (num) { Case 1://Private chat privatetalk (); Break Case 2://Public chat publictalk (); Break Case 3://Online System.out.println ("Current online numbers ...."); Showtalker (); Break Case 4://Downline downLine (); Flag=false; Ct.flag=false; Break }} s.close (); } catch (SocketException e) {} catch (IOException e) {e.printstacktrace (); }finally {}}private static void DownLine () {try {String msg = "null" + ":" + "null" + ":" + configs.msg_ex IT; Out.write (Msg.getbytes ()); } catch (IOException e) {e.printstacktrace (); }}private static void Showtalker () throws IOException {while (true) {String msg = "null" + ":" + "null" + ": "+configs.msg_onlist; Out.write (Msg.getbytes ()); Break }}private static void Publictalk () {System.out.println ("Currently in public chat mode ..."); try {while (true) {String msg = Sc.nextline (); if (Msg.equals ("-Q")) {break; } msg = "null" + ":" + msg + ":" + configs.msg_public; Out.write (Msg.getbytes ()); }} catch (IOException e) {e.printstacktrace (); }}private static void Privatetalk () {try {System.out.println ("Currently in private chat mode ..."); while (true) {String msg = Sc.nextline (); if ("-Q". Equals (msg)) {break; } msg = msg + ":" + configs.msg_private; Out.write (Msg.getbytes ()); }} catch (IOException e) {e.printstacktrace (); }}
}
The thread that the client reads the message from:
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.SocketException;
Import Clinet.untils.TimeUtil;
Import Configs.configs;
public class Clientthread extends Thread {
Private InputStream in;
Boolean flag=true;
Public Clientthread (InputStream in) {br/>this.in=in;
}
@Override
try {
while (flag) {
Byte[] Bys=new byte[1024];
int Len=in.read (bys);
String Client=new string (bys, 0, Len);
String[] Split=client.split (":");
String Sender=split[0];
String Msg=split[1];
int Msgtype=integer.parseint (split[2]);
Long Time=long.parselong (split[3]);
int num=1;
String data=timeutil.changemils2date (Time, "Yyyy-mm-dd HH:mm:ss");
if(msgType==Configs.MSG_PRIVATE) { //私聊 System.out.println(data); System.out.println(sender+"对你说:"+msg); }else if(msgType==Configs.MSG_PUBLIC) { //公聊 System.out.println(data); System.out.println(sender+"对大家说:"+msg); }else if(msgType==Configs.MSG_ONLINE) { System.out.println(sender+msg+data); }else if(msgType==Configs.MSG_ONLIST) { System.out.println(msg); }else if(msgType==Configs.MSG_EXIT) { System.out.println(sender+msg); } } } catch (SocketException e) { } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
}
Tools
Message type mode:
public class Configs {
//私聊//ctrl+shift+x :小转大//ctrl+shift+y:大转小public static final int MSG_PRIVATE = 100 ; //公聊public static final int MSG_PUBLIC = 200 ;//上线提醒public static final int MSG_ONLINE = 300 ;//在线列表public static final int MSG_ONLIST =400 ;//退出public static final int MSG_EXIT = 500 ;//文件public static final int MSG_FILE = 600 ;
}
The client input information is an integer tool:
Import Java.util.Scanner;
public class Inpututil {
public static int inputIntType(Scanner sc) { int choose = 0; while (true) { try { //录入用户输入的整数 choose = sc.nextInt(); break; } catch (Exception e) { sc = new Scanner(System.in); System.out.println("输入的类型不正确,请重新输入:"); } } return choose;}
}
Converts the number of milliseconds to the date format tool class:
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Public class Timeutil {
//2016-10-27 19:20:12 yyyy-mm-dd HH:mm:ss
public static string Changedate2week (string Datestr,string formatstr) {
SimpleDateFormat sdf = new SimpleDateFormat (FORMATSTR);
Date date = null;
try {
date = Sdf.parse (DATESTR);
} catch (ParseException e) {
E.printstacktrace ();
}
SimpleDateFormat sdf1 = new SimpleDateFormat ("E");
return Sdf1.format (date);
}
Convert the date of the string to a number of milliseconds public static long Changedate2mils (String datestr,string formatstr) {SimpleDateFormat SDF = new Simpledat Eformat (FORMATSTR); Date date = null; try {date = Sdf.parse (DATESTR); } catch (ParseException e) {e.printstacktrace (); } return Date.gettime ();} Convert the number of milliseconds to the specified format public static String changemils2date (Long mils,string formatstr) {SimpleDateFormat SDF = new SimpleDate Format (FORMATSTR); Date date = new Date (mils); return Sdf.format (date);} public static string Changedate2customermsg (String datestr) {Long mils = Changedate2mils (Datestr, "Yyyy-mm-dd_hh:mm:ss" ); Long nowmils = System.currenttimemillis (); Long offsetmils = nowmils-mils; String msg = ""; if (offsetmils<1000*60*2) {msg = "just"; }else if (offsetmils<1000*60*60) {msg = (offsetmils/(1000*60)) + "Minutes ago"; }else if (offsetmils<1000*60*60*24) {msg = (offsetmils/(1000*60*60)) + "Hour Ago"; }else if (offsetmils<1000*60*60*24*2) {msg= "Yesterday"; }else{String nowyear = changemils2date (nowmils, "yyyy"); String year = changemils2date (mils, "yyyy"); if (Nowyear.equals (year)) {msg = Changemils2date (mils, "MM month DD day"); }else{msg = changemils2date (mils, "yyyy year mm DD day"); }} return msg;
}
Service-Side---------------------------------------------------------------------------------------------------------------------- ----------------------------------
Service port import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.HashMap;
Import Usercheck.serverusercheck;
public class Serverdemo {
public static void main(String[] args) throws IOException { HashMap<String, Socket> hm = new HashMap<String,Socket>(); ServerSocket ss=new ServerSocket(1008); System.out.println("服务器已开启,正在等待客户端的连接..."); int i=1; while(true) { Socket s=ss.accept(); System.out.println("第"+(i++)+"个客户端已连接..."); InputStream in=s.getInputStream(); OutputStream out=s.getOutputStream();; ServerUserCheck su=new ServerUserCheck(s,hm); su.start(); }}
}
The thread on the server that holds the user name:
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.Socket;
Import Java.util.HashMap;
Import Java.util.Set;
Import Configs.configs;
Import Server.serverthread;
public class Serverusercheck extends Thread {
Private Socket S;
Private hashmap<string, socket> HM;
Private String username;
Public Serverusercheck (Socket s, hashmap<string, socket> hm) {this.hm = HM; THIS.S = s;} @Overridepublic void Run () {try {InputStream in = S.getinputstream (); OutputStream out = S.getoutputstream (); while (true) {byte[] bys = new byte[1024]; int len = In.read (bys); Username = new String (bys, 0, Len); if (!hm.containskey (username)) {hm.put (username, s); Out.write ("Yes". GetBytes ()); Break } else {out.write ("no". GetBytes ()); }} set<string> KeySet = Hm.keyset (); for (String key:keyset) {if (Key.equals (username)) {break; } String Online = Username + ":" + "online ..." + ":" + Configs.msg_online + ":" + system.currenttimemillis (); Socket s = hm.get (key); OutputStream OU = S.getoutputstream (); Ou.write (Online.getbytes ()); } New Serverthread (HM, S, username). Start (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}
}
The thread on which the server forwards information:
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.Socket;
Import Java.util.HashMap;
Import Java.util.Set;
Import Configs.configs;
public class Serverthread extends Thread {
Private hashmap<string, socket> hm;private Socket s;private String username;public serverthread (hashmap< String, socket> hm, Socket S, String username) {this.hm = HM; THIS.S = s; This.username = Username;} @Overridepublic void Run () {try {InputStream in = S.getinputstream (); OutputStream out = S.getoutputstream (); while (true) {byte[] bys = new byte[1024]; int len = In.read (bys); String client = new String (bys, 0, Len); string[] msgs = Client.split (":"); Receiver String receiver = msgs[0]; Message content String msgcontent = msgs[1]; Message type int msgtype = Integer.parseint (msgs[2]); After splitting the message, reassemble the message, and contract the server forwarding format//sender: Message content: Message type: Long time = System.currenttimemillis (); if (Msgtype = = configs.msg_private) {Socket s = hm.get (receiver); String zfmsg = Username + ":" +msgconTent + ":" + Msgtype + ":" + time; S.getoutputstream (). Write (Zfmsg.getbytes ()); } else if (Msgtype = = configs.msg_public) {set<string> KeySet = Hm.keyset (); for (String key:keyset) {if (Username.equals (key)) {continue; } Socket s = hm.get (key); String zfmsg = Username + ":" + msgcontent + ":" + Msgtype + ":" + time; S.getoutputstream (). Write (Zfmsg.getbytes ()); }} else if (Msgtype = = configs.msg_onlist) {set<string> KeySet = Hm.keyset (); StringBuffer sb = new StringBuffer (); int i = 1; for (String key:keyset) {if (Key.equals (username)) {continue; } sb.append (i++). Append (","). Append (Key). Append ("\ n"); } String zfmsg = Username + ":" + sb.tostring () + ":" + configs.msg_onlist + ":" + time; Socket s = hm.get (username); S.getoutputstream (). Write (Zfmsg.getbytes ()); }else if (msgtype==configs.msg_exit) {set<string> KeySet = Hm.keyset (); for (String key:keyset) {if (Key.equals (username)) {continue; } Socket OU = Hm.get (key); String zfmsg=username+ ":" + "Offline" + ":" +configs.msg_exit+ ":" +time; Ou.getoutputstream (). Write (Zfmsg.getbytes ()); } break; }} hm.get (username). Close (); Hm.remove (username); } catch (NumberFormatException e) {} catch (IOException e) {//TODO auto-generated catch block e.prints Tacktrace (); }}
}
Javase Project--------Chat Room