Java project: chat system
Today's java hands-on project is a simple chat room with simple interface and easy operation.
It is divided into three parts: registration system, login system and chat system. It is very suitable for java Xiaobai to practice.
Complete source code and material please pay attention to and private letter I get!
Interface display:
Code display:
package chatRoom2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Socket socket = null; try { socket = new Socket("127.0.0.1", 8000); new ClientWriterThread(socket).start(); new ClientReaderThread(socket).start(); } catch (Exception e) { e.printStackTrace(); } }
}
class ClientWriterThread extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ClientWriterThread(Socket socket) { super(); this.socket = socket; try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter( socket.getOutputStream()), true); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { while (true) { try { String str = in.readLine(); if (str == null || "exit".equals(str)) { break; } out.println(str); } catch (Exception e) { e.printStackTrace(); break; } } } @Override public String toString() { return "ClientWriterThread [socket=" + socket + "]"; }
}
class ClientReaderThread extends Thread {
private Socket socket;
private BufferedReader in;
public ClientReaderThread(Socket socket) { super(); this.socket = socket; try { in = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { while (true) { try { String str = in.readLine(); if ("exit".equals(str)) { break; } System.out.println("Server said:" + str); } catch (Exception e) { e.printStackTrace(); break; } } } @Override public String toString() { return "ClientReaderThread [socket=" + socket + "]"; }
}
Like this article can pay attention to me, I will continue to update, your attention is my update power! If you need more java learning materials, you can also private me!
I wish all the people who pay attention to me: good health, rich financial resources, good fortune like the East China Sea, long life than Nanshan Mountain, having a baby early and never losing their hair!