Java小項目之:聊天系統
今天給你們帶來的java練手小項目是一個簡單的聊天室,界面簡單,操做不難。
分爲註冊系統,登陸系統和聊天系統三部分,很適合java小白練手。
完整的源碼和素材請關注並私信我獲取!java
界面展現:
服務器
代碼展現:
package chatRoom2;socket
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;ide
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(); } }
}this
class ClientWriterThread extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;.net
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 + "]"; }
}code
class ClientReaderThread extends Thread {
private Socket socket;
private BufferedReader in;blog
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("服務器說:" + str); } catch (Exception e) { e.printStackTrace(); break; } } } @Override public String toString() { return "ClientReaderThread [socket=" + socket + "]"; }
}
喜歡這樣文章的能夠關注我,我會持續更新,大家的關注是我更新的動力!須要更多java學習資料的也能夠私信我!
祝關注個人人都:身體健康,財源廣進,福如東海,壽比南山,早生貴子,從不掉髮!get