JAvaプロジェクトの1つであるパブリックチャットルーム機能の実現


プロジェクト:公共チャットルームの機能の実現は、チャットに登録し、チャット記録を保存するなどの機能を実現した.
一、実現コード
1.クライアント
ChatClient.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class ChatClient {
	//     Socket
	private static Socket client = null;
	//        
	private static DataInputStream di = null;
	//        
	private static DataOutputStream dos = null;
	//   scanner      
	Scanner sc = new Scanner(System.in);
	//     String       
	static String name;
	//                    
	boolean falg = true;

	public static void main(String args[]) {
		//     
		ChatClient cc = new ChatClient();
		//       socket  
		client = new Socket();
		//     
		cc.connect();
		//     
		cc.send();
	}

	//   
	public void connect() {

		//       socket  
		client = new Socket();
		//     String  IP  
		String IP = null;
		//     int   
		int port = 0;
		System.out.println("***!!Welcome!!***");
		try {
			System.out.println("           0 127.0.0.1");
			//     IP   string   
			IP = sc.nextLine();
			//       IP,     IP     
			if (IP.equalsIgnoreCase("0")) {
				IP = "";
			}
			//      
			port = 8000;
		} catch (Exception e) {
		}
		try {
			//          ip  inetaddress   
			InetAddress address = InetAddress.getByName(IP);
			//      ip           
			InetSocketAddress socketaddress = new InetSocketAddress(address,
					port);
			//               
			try {
				//          
				client.connect(socketaddress);
				//        
				if (client.isConnected()) {
					//     
					runn();
				} else {
					client.connect(socketaddress);
					//     
					connect();
				}
			} catch (SocketException e) {
				System.out.println("        ,     ");
				//   connect()    
				connect();
			}
		} catch (Exception e) {
			System.out.println("        ,     ");
			//   connect()    
			connect();
		}
	}

	public void runn() {
		try {
			//   read  
			ClientThread read = null;
			//   read  
			read = new ClientThread();
			//   readdata    
			Thread readData = new Thread(read);
			//     DataInputStream       
			di = new DataInputStream(client.getInputStream());
			//     DataOutputStream       
			dos = new DataOutputStream(client.getOutputStream());
			//      
			while (falg) {
				System.out.println("      :");
				name = sc.next();
				System.out.println(name + "   ");
				System.out.println("       ,       /A");
				dos.writeUTF(name);
				dos.flush();
				read.setDataInputStream(di);
				//     
				readData.start();
				//   flag    
				falg = false;
			}
		} catch (IOException e) {

		}
	}

	//     
	@SuppressWarnings("deprecation")
	public void send() {
		//          
		System.out.println("     :");
		while (sc.hasNext()) {
			String mess;
			mess = sc.nextLine();
			if (mess.equalsIgnoreCase("/0")) {
				System.exit(0);
			} else if (mess.equalsIgnoreCase("/D")) {
				try {
					File file = new File("qq.txt");
					di = new DataInputStream(new FileInputStream(file));
					String info = null;
					System.out.println("1   ;2   ;3   ;4   ;5   ~;");
					System.out.println("6   ;7   ;8   ;9   ;10   ;");
					System.out.println("     :");
					String age = sc.next();
					while ((info = di.readLine()) != null) {
						StringTokenizer stri = new StringTokenizer(info, ".");
						String inn = stri.nextToken();
						String in = stri.nextToken();
						// System.out.println(in);

						if (age.equals(inn)) {
							dos.writeUTF(in);
							break;
						}
					}
				} catch (Exception e) {
					
				}
			}
			if (mess.equals("/D")) {
				System.out.println("     :");
			} else {
				select(mess);
			}
		}
	}

	//          
	public void select(String mess) {
		//        
		if (mess.equalsIgnoreCase("/A")) {
			//      helpList()  
			helpList();
		} else if (mess.equalsIgnoreCase("/C")) {
			try {
				System.out.println("               ");
				String str1 = sc.next();
				File file = new File(str1 + ".txt");
				BufferedReader bf = new BufferedReader(new FileReader(file));
				String str = null;
				while ((str = bf.readLine()) != null) {
					System.out.println(str);
				}
				bf.close();
			} catch (IOException e) {

			}

		} else {
			try {
				//          
				dos.writeUTF(mess);
				//      
				dos.flush();
			} catch (IOException e) {

			}
		}
	}

	public void helpList() {
		System.out.println("  :     ,    !!");
		System.out.println("/B       ,  /     ,/C       ,/D     ,/0     ");
	}
}

ClientThread.java
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ClientThread implements Runnable {
	//     DataInputStream  
	DataInputStream di;
	//     string            
	String str;
	boolean ff=true;

	public void setDataInputStream(DataInputStream di) {
		this.di = di;
	}

	public void run() {
		while (true) {
			try {
				//        
				str = di.readUTF();
				//   writeFile        
				writeFile(str);
				//     
				System.out.println(str);
			} catch (IOException e) {
				//                
				System.out.println("    ~~~~~~~");
				//      
				System.exit(0);
			}
		}
	}
 
	public void writeFile(String str2) {
		try {
			//       
			File file = new File(ChatClient.name + ".txt");
			FileWriter fw = new FileWriter(file, true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(str2);
			//         
			bw.newLine();
			//      
			bw.close();
			//        
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 

2.サービス側
ChatServer.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
	//     serversocket  
	private static ServerSocket server = null;
	//     socket  
	private static Socket client = null;
	//                  
	private static String name;
	//          
	private static boolean falg = true;
	//        
	private static DataInputStream di = null;
	//        
	private static DataOutputStream dos = null;

	public static void main(String args[]) {
	//   ServerThread  
	ServerThread st = new ServerThread();
	while (true) {
		try {
			//   serversocket        8000
			server = new ServerSocket(8000);
		} catch (IOException e) {
			System.out.println("    !!");
		}
		try {
			System.out.println("       ....");
			//                     
			client = server.accept();
			System.out.println("    !!");
			//            DataInputStream 
			di = new DataInputStream(client.getInputStream());
			//            DataInputStream 
			dos = new DataOutputStream(client.getOutputStream());
			//         
			while (falg) {
				name = di.readUTF();
				if (st.checkp(name)) {
					System.out.println("     :" + client.getInetAddress()+ "\t" + name + ":     ");
					//  falg  false
					falg = false;
				} else {
					//      
					dos.flush();
				}
			}
		} catch (IOException e) {
			System.out.println("         ......");
		}

		//               
		if (client.isConnected()) {
			//                
			ServerThread sth = new ServerThread(client, name);
			Thread th = new Thread(sth);
			//     
			th.start();
			falg = true;
			}
		}
	}
}

ServerThread.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

public class ServerThread implements Runnable {
	//     socket  
	Socket client = null;
	//     Datainputstream  
	DataInputStream di = null;
	//     Dataoutputstream  
	DataOutputStream dos = null;
	//                   
	String name = null;
	//     hashtable                    
	static Hashtable<String, ServerThread> clientlist = new Hashtable<String, ServerThread>();

	public ServerThread() {
		
	}

	public ServerThread(Socket client, String name) {
		try {
			//     client        client
			this.client = client;
			//     name        name
			this.name = name;
			//            DataInputStream 
			di = new DataInputStream(client.getInputStream());
			//            DataOutputStream 
			dos = new DataOutputStream(client.getOutputStream());
		} catch (IOException e) {
			
		}
	}

	public void run() {
		try {
			//        hashtable
			clientlist.put(name, this);
			//                 
			sendallClient(name + "     ");

			while (true) {

				//     string             
				String mess = di.readUTF();
				//     stringtokenizer          
				StringTokenizer str = new StringTokenizer(name, "/");
				//              
				//                 
				if (str.countTokens() == 2) {
					//               
					String nameid = str.nextToken();
					//           
					String message = str.nextToken();
					//    sendclient     
					sendClient(nameid, message);

					//                        
				} else if (mess.equalsIgnoreCase("/B")) {
					//      getlist  
					getList();
					//        -change  
				} else if (mess.equalsIgnoreCase("/0")) {
					System.out.println("name" + "     ");
					break;
				} else if (str.countTokens() == 1 || str.countTokens() >= 3) {
					//   sendallclient      
					sendallClient(name + " :" + mess);
				} 
			}
			client.close();
		} catch (Exception e) {

		} finally {
			//        
			clientlist.remove(name);
			File file = new File(name + ".txt");
			//     
			file.delete();
			//      ,          
			sendallClient(name + "     ");
			System.out.println(getDate() + " " + name + "     ");
		}
	}

	//   
	public void sendallClient(String mess) {
		//   clientlist   ServerThread       
		Enumeration<ServerThread> allclients = clientlist.elements();
		//       
		while (allclients.hasMoreElements()) {
			//         ,          
			ServerThread st = (ServerThread) allclients.nextElement();
			try {
				//        
				st.dos.writeUTF(getDate() + "\t" + mess);
				//    
				st.dos.flush();
			} catch (IOException e) {
				Thread th = new Thread(st);
				//          
				th.interrupt();
			}
		}
	}

	//   
	public void sendClient(String name1, String mess) {
		ServerThread st = clientlist.get(name1);
		ServerThread st1 = clientlist.get(name);
		try {
			//             
			st.dos.writeUTF(getDate() + "\t" + name + "   :\t" + mess);
			//    
			st.dos.flush();

			//          
			st1.dos.writeUTF(getDate() + "\t  " + name1 + " :\t" + mess);
			//    
			st1.dos.flush();
		} catch (IOException e) {

			System.out.println("        ,     !");
			//sendClient(name1, mess);
		}
	}

	public boolean checkp(String str) {
		boolean flag = true;
		//         
		Enumeration<String> checkname = clientlist.keys();
		//        
		while (checkname.hasMoreElements()) {
			//         ,          
			String sn = (String) checkname.nextElement();
			//          ,      false
			if (str.equalsIgnoreCase(sn)) {
				//   false
				flag = false;
				//          
			} else if (str.equalsIgnoreCase("")) {
				//   false
				flag = false;
			}
		}
		return flag;
	}

	//      
	public void guanBi() {
		if (!(client == null)) {
			try {
				client.close();
				System.out.println("        ");
			} catch (IOException e) {

			}
		}
	}

	//       
	public void getList() {
		//         
		Enumeration<String> checkname = clientlist.keys();
		//            
		ServerThread st = clientlist.get(name);
		try {
			//     
			st.dos.writeUTF("      ");
			//         
			st.dos.writeUTF(clientlist.size() + ":   ");
		} catch (IOException e1) {

			e1.printStackTrace();
		}
		//     
		while (checkname.hasMoreElements()) {
			//         ,          
			String sn = (String) checkname.nextElement();
			try {
				//          
				st.dos.writeUTF("    :" + sn);
				//      
				st.dos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//   
	public String getDate() {
		//   data  
		Date nowTime = new Date();
		//        
		String pattern = "HH:mm:ss";
		//   SimpleDateFormat  
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		//           
		String timePattern = sdf.format(nowTime);
		//       
		return timePattern;
	}
}

二、補充
1.制作bat実行ファイル
クライアントの作成バートとserverbat,編集.batファイルはjava-jar client.jarとjava-jar server.jar