Socket application in Java

Source: Internet
Author: User
Tags readline thread class
The socket is one end of two-way communication between two programs running on the network, it can accept the request, also can send the request, can use it to write the data on the network more conveniently. In Java, there is a special socket class to handle the user's request and response. Using the method of the socket class, you can realize communication between two computers. Here is how to use socket for network programming in Java.

In Java, the socket can be understood as a special object on the client or server side, which has two key methods, one is the getInputStream method and the other is the Getoutputstream method. The getInputStream method can get an input stream, and the input stream obtained by the getInputStream method on the client's socket object is actually the data stream sent back from the server side. The Getoutputstream method gets an output stream, and the output stream returned by the Getoutputstream method on the client socket object is the data stream that will be sent to the server side (in fact, a buffer that temporarily stores the data that will be sent in the past).

Programs can further encapsulate these data streams as needed. The examples in this article encapsulate these data streams (the encapsulation can refer to the implementation part of Java streaming).

To better illustrate the problem, here is an example of an online conversation, the client started, the server will start a thread to communicate with the customer text.

To complete this work, three parts of the work need to be completed, which in turn illustrates:

First, establish the server class

In Java, there is a class that is designed to create a socket server, called ServerSocket, that can be used as a parameter for creating a server object using the port number that the server needs to use.

ServerSocket Server = new ServerSocket (9998)

This statement creates a server object that uses port number No. 9998. When a client program establishes a socket connection and the port number that is connected is 9998, the server object Server responds to the connection and the Server.accept () method creates a socket object. The server side can use this socket object to communicate with the customer.

Socket incoming = Server.accept ()

The input stream and the output stream are obtained and encapsulated

BufferedReader in = new BufferedReader (new
InputStreamReader (Incoming.getinputstream ()));
PrintWriter out = new PrintWriter (Incoming.getoutputstream (), true);

You can then use the In.readline () method to get input from the client, or you can use the Out.println () method to send data to the client. This allows the client to respond to different requests based on the needs of the program.

The two streams should be closed after all traffic is closed, in order to close the output stream first and then close the input stream, that is, using the

Out.close ();
In.close ();
Second, the establishment of client code

Compared to the server side, the client is simpler, and the client simply creates a socket object with the IP of the server's machine and the port of the server as a parameter. After you get this object, you can use the method described in the "Building a Server" section to implement data input and output.

Socket socket = new Socket ("168.160.12.42", 9998);
in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
out = new PrintWriter (Socket.getoutputstream (), true);

The above program code establishes a socket object that is connected to a server object with an IP address of 168.160.12.42 and a port of 9998. and the input stream and output stream are established, respectively corresponding to the output of the server and the client writing.

Third, the establishment of user interface

Readers can build their own user interface according to their preferences, which is not the focus of this article.

Through the above three steps, we can establish a simple dialog program. However, to make this procedure more complete, the following improvements should be made:

First, the server can only serve one customer, that is, a single thread. It can be improved to a multithreaded server.

Try
{file://Establish a server
ServerSocket Server = new ServerSocket (9998);
int i=1;
for (;;)
{
Socket incoming = Server.accept ();
New Serverthread (Incoming,i). Start ();
i++;
}
}catch (IOException ex) {ex.printstacktrace ();}

Loop to detect if a customer is connected to the server, and if so, create a thread to service the customer, the name of which is Serverthread, which extends the thread class, which is written the same way as the server described above.

Second, in order to be able to get the message from the other side at any time, you can set up a separate thread in the server and the client to see the input stream, if there is input in the input stream, you can display it instantly. The code is as follows:

New Thread ()
{
public void Run ()
{
Try
{
while (true)
{
Checkinput ();
Sleep (1000);//Every 1000 milliseconds detected
}
}catch (Interruptedexception ex)
{
}catch (IOException ex)
{
}
}
}.start ();

where the Checkinput () method is
private void Checkinput () throws IOException
{
String Line;
if ((Line=in.readline ())!=null) file://detect if there is new data in the input stream
T.setpartner (line); file://the messages in the data stream
}


Through the above improvements, the program can be better run.

Attached: Implementation code for the server

Import java.net.*;
Import java.io.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;

public class Talkserver
{public static void main (string[] args)
{Try
{file://Establish a server
ServerSocket Server = new ServerSocket (9998);
int i=1;
for (;;)
{Socket incoming = server.accept ();
New Serverthread (Incoming,i). Start ();
i++;
}
}catch (IOException ex) {
Ex.printstacktrace ();
}
}
}

Class Serverthread extends Thread implements ActionListener
{
private int threadnum;
private socket socket;
Talkserverfrm T;
BufferedReader in;
PrintWriter out;
Private Boolean talking=true;
Public Serverthread (Socket s,int c)
{threadnum = c;
Socket = s;
}

public void actionperformed (ActionEvent e)
{Object Source = E.getsource ();
try{
if (source==t.btnsend)
{out.println (T.gettalk ());
T.cleartalk ();
}else
if (source==t.btnend)
{out.println ("The conversation process is terminated by the other");
Out.close ();
In.close ();
Talking = false;
}
}catch (IOException ex) {
}
}

public void Run ()
{try{
T=new talkserverfrm (New Integer (threadnum). ToString (), this);
T.setsize (500,500);
T.show ();
in = new BufferedReader (new
InputStreamReader (Socket.getinputstream ()));
out = new PrintWriter (Socket.getoutputstream (), true);
}catch (Exception e) {
}
New Thread ()
{public void Run ()
{try{
while (true)
{checkinput ();
Sleep (1000);
}
}catch (Interruptedexception ex) {
}catch (IOException ex) {
}
}
}.start ();
while (talking)
{ }
T.dispose ();
}

private void Checkinput () throws IOException
{String line;
if ((Line=in.readline ())!=null)
T.setpartner (line); file://this is the method in the interface class,
file://is used to output line content to the user interface
}
}

Java is a language that can be used for network programming, and it provides two powerful network support mechanisms: URLs that access network resources and classes that communicate with sockets to meet different requirements. One is the use of URLs to access Internet resources, the other is for the application of Client/server (client/server) mode and the implementation of some special protocols, its communication process is based on the TCP/IP protocol Transmission layer Interface socket implementation. This article wants to briefly introduce the Java implementation method of socket programming.

Most of the communication components that customers use between servers are based on socket interfaces. The socket is a network communication endpoint between two programs for two-way data transmission, with an address and a port number to identify. Each service program is serviced in a single port, and the client who wants to use the service must also connect to that port. Socket because it is based on the transport layer, so it is relatively primitive communication protocol mechanism. Through the data representation of the socket is the word throttling information, so the communication between the two sides to complete a specific application must be in accordance with the way the two parties agreed to format and explain the data, we can see that the use of socket programming is more cumbersome, but it has more flexibility and a wider use of the field.

Some friends ask, what is the pattern of client/server work? OK, now I'd like to combine a picture to describe their working mode.



So how does a Java application implement the above process? The java.net package has two classes of sockets and ServerSocket, which are used to create socket traffic on both the client and server.

Let's take a look at the process written by the client segment:

1, first call the socket class constructor, with the server's specified IP address or the specified host name and the specified port number as parameters, create a socket stream, in the creation of the socket stream contains the request to the server to establish a communication connection process implementation.

2, established the client communication socket after. You can use the method getInputStream () and Getoutputstream () of the socket to create an input/output stream. In this way, after using the socket class, the network input output is also transformed into the process of using the Stream object.

3. Read and write throttling data using the corresponding method of the input output stream object, because the socket,socket used for the communication is the endpoint that establishes the connection with the server, so the data will be obtained from the server or sent to the server via the connection. At this time we can to the byte stream data according to the agreement between the client and server processing, complete the communication task between the two parties.

4. After the communication task is completed, we use the close () method of the stream object to turn off the input and output stream for network communication, and close the socket with the closed () method of the socket object.

Below, I want to use a simple example to further explain the client program writing

Code One:

Import java.io.*;

Import java.net.*;

public class Socketcommunicationclient

{

public static void Main (string[] args)

{

try{

Socket clientsocket =new socket ("mice", 9000);//Create a stream Socket and connect to port 9000 on the host mice

OutputStream output Stream =clientsocket.getoutputstream ()//write byte to this socket

DataInputStream input=new DataInputStream (Clientsocket.getinputstream ());

FILE://creates a new data input stream to read data from a specified input stream

int C;

String response;

See, this is the dead loop where the client listens for user input all the time.
while ((c= System.in.read ())!=-1)//takes the input string from the screen and decomposes it into characters

{

Output.write ((byte) c);

if (c== '/n ')//If the character is carriage return, the output string buffer

{

Output.flush ();

Response=input.readline ();

SYSTEM.OUT.PRINTLN ("Communication:" +response);

}

}

Output.close ();

Input.close ();

Clientsocket.close ();

catch (Exception e) {

System.err.println ("Exception:" +e);

}

}

}

This program is a very simple example of data communication, the program first creates a socket and connects to port 9000 on the host mice, then opens the input output stream, and the program receives characters from the standard input and writes to the stream, each full line (marked by the user typing the carriage return), The string in the buffer is sent to the server-side program on the mice for processing, waiting for the server-side response. The Input.readline () method call will cause the program to stall until an answer is received, and the program will repeat the process until the user enters the abort character. The final program to close the socket input output stream, in the closed socket and server-side connection.
Above we saw how to use Java to write the client socket interface program, I would like to briefly talk about the server-side socket Interface Program Java implementation method, the process is as follows:

1, first call the ServerSocket class to a port number as a parameter, create a ServerSocket object, that is, server-side service program on the specified port listening to the socket.

2, the server-side program uses the ServerSocket object's accept () method, receives the connection request from the client program, at this time the server side will remain stagnant until receives the client to send the connection request, this method will return a new socket class instance, Represents a communication link that is established with the client in the service program's communication endpoint. If you are using Java multithreaded programming, you can implement concurrent servers and continue to listen for connection requests from other customers.

3, use the new socket object to create input, output stream objects.

4, using the method of streaming object and the data transmission of the client, identify and process the request data from the client according to the agreed Protocol, and return the processing result to the client.

5. After the client has finished working, the server-side program shuts down the stream and the communication socket of the client communication.

6. Between the end of the server program, you should close the socket used for listening.

Let's look at the Java implementation of a server-side program:

Code two:

Import java.net.*;

Import java.io.*;

public class Socketcommunicationserver

{

public static void Main (string[] args)

Try

{

Boolean flag=true;//set flag bit to True

Socket client=null;//creates a socket client to receive requests from the client

String Inputline;

ServerSocket serversocket =new ServerSocket (9000);//Create a server socket with Port 9000

SYSTEM.OUT.PRINTLN ("Server listens on port 9000");

FILE://can also use Serversocket.getlocalport () to get the port number

while (flag)

{

Client=serversocket.accept ();

FILE://listens and accepts a connection to this socket, blocking the method until a connection is generated

DataInputStream input=new DataInputStream (New Bufferedinputstream (Client.getinputstream ()));

PrintStream output=new PrintStream (New Bufferedoutputstream (Client.getoutputstream ());

while ((Inputline= input.readline ())!=null)

{

if (Inputline.equals ("Stop"))

{

Flag=false;

Break

}

Output.println (Inputline);

Output.flush ();

}

Output.close ();

Input.close ();

Client.close ();

}

Serversocket.close ();

}catch (IOException e) {}

}

}

}
----------------------------------------------------------------------------------------

Here simple to say how to achieve similar to QQ chat that kind of function, in fact Tencent QQ is based on UDP, rather than TCP, we are here purely to cover up this interaction, so, first use the next bar.

Client:

The client has read, has written.

The realization of the read operation is to read the data through the getInputStream method in an infinite loop or a method called once every few minutes.

Write operation, is the same, there is a cycle, has been listening to the input of our clients, monitor the content to send data to the server.

Service side:

In addition to reading and writing similar to the client, there is a multiple client problem, the problem is very simple, we can start a corresponding thread for each client.

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.