Use Socket in Java to implement client chat programs

Source: Internet
Author: User
Tags readline socket

Socket is the most basic communication interface in network programming. It is implemented based on Socket at the underlying layer of commonly used network auxiliary classes, such as URLs.

Socket, in the image, is the two ends of the connection, for example, S <=> S, the middle channel is the network, and simply use Socket, we can implement a simple chat function.

The specific effect is shown in the figure below:

This is just a try in the local environment. If you add the UI interface, you can actually make a chat application.

1. The Server mainly uses the ServerSocket accept method to wait for the client connection. If the client has not been connected, it will wait until the client request arrives.

The client is a Socket. When a request arrives from the client, accept returns a Socket object, which is the one on the left of S <=> S, you can use InputStream and OutputStream to read and write data. Read is the message received, and write is the reply information.

The code is as follows: Copy code

Public class Server {

Public static void main (String [] args ){

Try {

ServerSocket server = new ServerSocket (9999 );

Helper. println ("Server started, waiting for message .");

Socket client = server. accept ();

PrintWriter pw = null;

While (true ){

BufferedReader br = new BufferedReader (new InputStreamReader (

Client. getInputStream ()));

String content = br. readLine ();

If (content. equals ("end ")){

Server. close ();

Br. close ();

If (pw! = Null ){

Pw. close ();

}

Break;

}

Helper. println (content );

Helper. print ("Server :");

Pw = new PrintWriter (client. getOutputStream (), true );

BufferedReader in = new BufferedReader (new InputStreamReader (System. in ));

String output = "Server:" + in. readLine ();

Pw. println (output );

Pw. flush ();

}

Helper. println ("Client left! Server Closed .");

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

}

2. the Client is a Socket and defines the connection address and port. The address indicates the host on the network, and the port indicates the application on the host, obviously, it is the above Server application, because it defines the port that it is waiting to listen to is 9999. when a Socket object is created and the address and port are specified, a request is sent to the corresponding Server to request connection. If the connection is successful, you can continue, or directly throw an exception. Of course, the connection is successful. The Server must be listening first. [Java] view plaincopy

The code is as follows: Copy code

Public class Client {

Public static void main (String [] args ){

Try {

Socket client = new Socket ("127.0.0.1", 9999 );

PrintWriter pw = null;

InputStreamReader isr = null;

Helper. println ("Client started, ready to write content .");

String input = "";

While (true ){

Helper. print ("Client :");

InputStream is = System. in;

Input = new BufferedReader (new InputStreamReader (is ))

. ReadLine ();

Pw = new PrintWriter (client. getOutputStream (), true );

Pw. println ("Client:" + input );

If (input. equals ("end ")){

Client. close ();

Is. close ();

Pw. close ();

If (isr! = Null ){

Isr. close ();

}

Break;

}

Isr = new InputStreamReader (client. getInputStream ());

Helper. println (new BufferedReader (isr ). ReadLine ());

}

Helper. println ("Client stopped! ");

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

}

Ps: Java.net. socket inherits from java. lang. object, there are eight constructors, the method is not much, the following describes the use of the most frequent three methods, other methods you can see the JDK-1.3 documentation.
The. Accept method is used to generate "blocking" until a connection is received and a client's Socket object instance is returned. "Blocking" is a term that enables the program to run temporarily "stay" in this place until a session is generated and then the program continues. Generally, "blocking" is produced by a loop.
The. getInputStream method obtains the network connection input and returns an InputStream object instance.
The other end connected by the. getOutputStream method will get the input and return an OutputStream object instance.
Note: The getInputStream and getOutputStream methods both generate an IOException, which must be captured because the returned stream objects are usually used by another stream object.

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.