Java -- & gt; implements the group chat function (C/S mode -- TCP protocol), java ---- tcp

Source: Internet
Author: User

Java --> implement the group chat function (C/S mode -- TCP protocol), java ---- tcp

--> Java supports TCP:

--> The java.net package defines two types of ServerSocket and Socket, which are used to implement two-way connection between the server and client respectively.

--> Client class definition Client

Package com. dragon. java. tcpchat; import java. io. IOException; import java.net. socket; import java.net. unknownHostException;/*** Client ** @ author Auser **/public class Client {public static void main (String args []) throws UnknownHostException, IOException {Socket client = new Socket ("192.168.1.188", 10000); // new ClientSend (client) thread that sends the information of the wearable device ). start (); // create the thread for receiving information new ClientReceive (client ). start ();
// The output stream and client cannot be closed because the chat function is implemented instead of sending information only once. // Client. shutdownOutput (); // client. close ();}}

--> The ClientSend class defines the thread in which the client sends information to the server.

Package com. dragon. java. tcpchat; import java. io. IOException; import java. io. printStream; import java.net. socket; import java. util. threads;/*** the Thread from which the client sends messages to the server ** @ author Auser **/public class ClientSend extends Thread {private sockets; private Socket socket; public ClientSend (Socket socket) {this. socket = socket ;}@ Override public void run () {response = new response (System. in); try {PrintS Tream ps = new PrintStream (socket. getOutputStream (); String line = ""; // blocked message sending while (line = response. nextLine ())! = Null) {ps. println (line) ;}} catch (IOException e) {e. printStackTrace ();}}}

--> The ClientReceive class defines the thread in which the client receives server information.

Package com. dragon. java. tcpchat; import java. io. bufferedReader; import java. io. inputStreamReader; import java.net. socket;/*** Thread for receiving information from the client ** @ author Auser **/public class ClientReceive extends Thread {private Socket socket; public ClientReceive (Socket socket Socket) {this. socket = socket ;}@ Override public void run () {try {BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputSt Ream (); // receives information by line String line = ""; while (line = br. readLine ())! = Null) {System. out. println (line) ;}} catch (Exception e) {e. printStackTrace ();}}}

--> Server class definition Server

Package com. dragon. java. tcpchat; import java. io. IOException; import java.net. serverSocket; import java.net. socket; import java. util. arrayList; import java. util. list;/*** Server ** @ author Auser **/public class Server {public static void main (String [] args) throws IOException, interruptedException {List <Socket> list = new ArrayList <> (); // create a server Socket ServerSocket server = new ServerSocket (10000); while (True) {// method of blocking the receiving client Socket = server. accept (); // It is designed that multiple threads may add or delete the set. synchronous processing of synchronized (list) {list. add (socket) ;}// start a new thread to process the communication between the client, new HandleSocket (socket, list ). start () ;}// because the client does not know when to send the message, the server must be enabled and cannot be closed. }}

--> HandleSocket class is used to operate clients connected to the server (online/offline notifications, blocking and blacklisting, and sending information to each client, etc ...)

Package com. dragon. java. tcpchat; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. printStream; import java.net. inetAddress; import java.net. socket; import java. util. list;/*** process the Thread of each (single) Client Connected to the server ** @ author Auser **/public class HandleSocket extends Thread {private Socket socket; private List <Socket> list;/***** constructor ** @ param socket * currently connected Client * @ param list * stores the set of connected clients */public HandleSocket (Socket socket, List <Socket> list) {this. socket = socket; this. list = list;}/*** thread run Method */@ Override public void run () {InetAddress address = socket. getInetAddress (); // obtain the address of the client connected to the Server String ip = address. getHostAddress (); System. out. println (ip + "launched! "); If (ip. equals (" 192.168.1.117 ") {synchronized (list) {sendToAll (ip +" has been blacklisted due to illegal operations! "); List. remove (socket) ;}return ;}try {BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (), "gbk"); String line = ""; while (line = br. readLine ())! = Null) {String msg = ip + ":" + line; System. out. println (msg); // output to the console of the server // send what the client says to all other clients sendToAll (msg) ;}} catch (IOException e) {// e. printStackTrace (); System. out. println (ip + "offline! "); Synchronized (list) {list. remove (socket) ;}}/ *** send the information to all clients, remove the information sent by the current socket ** @ param msg */private void sendToAll (String msg) {synchronized (list) {for (Socket s: list) {if (s! = Socket) {try {PrintStream ps = new PrintStream (s. getOutputStream (); ps. println ();} catch (IOException e) {e. printStackTrace ();}}}}}}

--> Note: To connect the client to the server, you must first find the server. Therefore, the server must be enabled before enabling the server...

--> This is a weak LAN chat function...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.