c/S chat room for simple command line interface

Source: Internet
Author: User


In recent days reviewed the next Java Network programming socket use I think that although the following content is very basic but if you want to make a good thing and want to learn quickly, we must first lay the foundation

If the foundation is good, then learning new knowledge in the future will be very fast, in fact, all the same.

If the great God can play under, expand under the perfect under the function that is better, please leave your idea below I will always maintain these articles.

TCP Protocol Basics

The IP protocol is a key protocol for the use of the Internet, the full name of Internet Protocol, the Internet protocol is often referred to as IP protocol through IP protocol, which makes the Internet a network that allows different operating systems to connect different types of computers. If you want to communicate with two computers then use the same language then the IP protocol but only to ensure that the computer can send to accept packet data, the IP protocol is responsible for sending messages from one host to another host, the message is split into packets during transmission. However, it only solves the problem of sending and receiving data between them, but it does not solve the problems of data grouping in the transmission process. Therefore, it is necessary to use the TCP protocol to ensure reliable and error-free communication services.

The TCP protocol is a connection-oriented end-to-end protocol. This is because he plays an important role in the link between the two computers. Established links for virtual links to send and receive data

The functions of TCP and IP protocols are different and can be used separately, but they are designed as a protocol at the same time and are functionally complementary. Only the combination of the two can ensure that the Internet in the complex environment of the normal operation of all the computers to be connected to the Internet must both install and use both protocols so sing it. These two protocols are called TCP/IP protocols.

Using ServerSocket to create a TCP server side

Before a virtual link is established between two communication entities, there must first be a communication entity that proactively accepts connection requests from other entities. The class in Java that receives other communication entity connection requests is serversocket,serversocket to listen for connections from the socket, and if there is no connection, he will always be in a wait state, ServerSocket contains a method to listen for requests from the client

Socket Accept (): If a request for a link to a client's socket is received, the method returns a socket corresponding to the client or the method has been waiting for the thread to be blocked

To create a serversocket pair of images, the following constructors are provided

ServerSocket (int port) specifies the port to create a ServerSocket pair like that port should have a valid port integer

ServerSocket (int port,int backlog): Add a parameter backlog to change the length of the connection queue

When ServerSocket is finished, you should close the ServerSocket using the Close () method of ServerSocket. Under normal circumstances

The server does not have to be reformed to accept a client's request, but should constantly accept all requests from the client, so the Java program will usually cycle the call ServerSocket's accept () method

Using the socket for communication

The client can usually connect to the specified server using the socket's constructor, which can usually be connected to the appropriate host using a given two constructors or to a server of the corresponding IP address so that the dialog can be implemented

--

Join multithreading

The previous server and client had only a simple communication operation: After the server received the client connection, the server output a string to the client, and the client just read the server-side string and exited. Clients in real-world applications may maintain long-time communication on demand and on the server side, that is, the server needs to constantly read client data and write data to the client, and the client needs to constantly read the server-side data and write data to the server.

When reading data using the traditional Bufferreader ReadLine () method, the thread is blocked and the program cannot execute until the method returns successfully. With this in mind, the server should start a thread for each socket and each thread is responsible for communicating with one client

The county where the client reads the server-side data is also blocked, so the system should start a thread separately. This thread is specifically responsible for reading the server-side data.

Now consider implementing a command-line interface of the C/S Chat room application, the server should contain multiple threads, each socket corresponding to a thread, the thread is responsible for reading the socket corresponding input stream data. and send the read data to each socket output stream once (broadcast one client's data to other clients) need to save all sockets on the server side using list

Server-side implementations:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >package Com.example.administrator.openinternet;import Java.io.ioexception;import Java.net.ServerSocket;import Java.net.socket;import Java.util.arraylist;import Java.util.collection;import Java.util.Collections;import java.util.list;/** * Created by Administrator on 2015/7/23. * Server-side program */public class Javasocket {public    static list<socket> socketlist = Collections.synchronizedlist (new Arraylist<socket> ());    public static void Main (String [] args) throws IOException {        ServerSocket ss = new ServerSocket (30000);        while (true)        {            Socket s = ss.accept ();            Socketlist.add (s);            New Thread (new Serverthread (s)). Start ();}}    </span></span>

Thread classes on the server side:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >package Com.example.administrator.openinternet;import Java.io.bufferedreader;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.printstream;import Java.net.socket;import java.net.SocketException ;/** * Created by Administrator on 2015/7/23.    * Server-side thread */public class Serverthread implements Runnable {Socket s = null;    BufferedReader br = null;        Public Serverthread (Socket s) {this.s = s; try {br = new BufferedReader (New InputStreamReader (S.getinputstream ()));//create and read stream} catch (IOException E        ) {e.printstacktrace (); }}/** * starts executing the active part of the class ' Code. This method was * called when a thread was started that had been created with a class which * implements {@code Runn     Able}.            */@Override public void Run () {try {String content = null; while (content= Readfromclient ())!=null) {for (Socket s:javasocket.socketlist) {                PrintStream PS = new PrintStream (S.getoutputstream ());        }}}catch (IOException e) {e.printstacktrace ();        }} private String readfromclient () {try {return br.readline ();            }catch (IOException e) {e.printstacktrace ();    JavaSocket.socketList.remove (s);//Remove data from Socketlist three} return null; }}</span></span>
Client implementations:

<span style= "FONT-SIZE:18PX;" >package Com.example.administrator.openinternet;import Java.io.bufferedreader;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.printstream;import java.net.socket;/** * Created by Administrator on 2015/7/23. * My client's program */public class MyClient {public    static void Main (String [] args) throws IOException    {        Socket s = n EW Socket ("127.0.0.1", 30000);        New Thread (new Clientthread (s)). Start ();        PrintStream PS = new PrintStream (S.getoutputstream ());        String line = null;        BufferedReader br = new BufferedReader (new InputStreamReader (system.in));        while (line = Br.readline ())!=null)        {            ps.println (line);}        }    } </span>

Client Thread:

<span style= "FONT-SIZE:18PX;" >package Com.example.administrator.openinternet;import Java.io.bufferedreader;import java.io.IOException; Import Java.io.inputstreamreader;import java.net.socket;/** * Created by Administrator on 2015/7/23.    * Client thread */public class Clientthread implements Runnable {private Socket s;    BufferedReader br = null;        Public Clientthread (Socket s) throws IOException {this.s = s;    br = new BufferedReader (New InputStreamReader (S.getinputstream ())); }/** * Starts executing the active part of the class ' Code. This method was * called when a thread was started that had been created with a class which * implements {@code Runn     Able}.            */@Override public void Run () {try {String content = null;            while (content = Br.readline ())!=null) {System.out.println (content);        }}catch (Exception e) {e.printstacktrace (); }   }}</span> 

This enables a simple reply, in fact, can continue to expand such as the implementation of client and server-side data delivery over a few days to update


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

c/S chat room for simple command line interface

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.