Java Network Programming Using Socket

Source: Internet
Author: User

A Socket is the end of bidirectional communication between two programs running on the network. It can accept or send requests and conveniently write data transmission over the network. In Java, there are specialized Socket classes to process user requests and responses. By using the Socket method, communication between two computers can be realized. This section describes how to use Socket for network programming in Java.

In Java, Socket can be understood as a special object on the client or server. This object has two key methods: The getInputStream method and the getOutputStream method. The getInputStream method can get an input stream. The input stream obtained by the getInputStream method on the Socket object of the client is actually the data stream sent back from the server. The GetOutputStream method gets an output stream. The output stream returned by the getOutputStream method on the client Socket object is the data stream to be sent to the server. (It is actually a buffer zone that temporarily stores the data to be sent ).

The program can further encapsulate these data streams as needed. The example in this article encapsulates these data streams (for more information about encapsulation, see Java streaming implementation ).

To better illustrate the problem, here is an example of an online conversation. After the client is started, the server starts a thread to communicate with the client.

To complete this task, you need to complete the work in three parts:

1. Create a server class

Java has a class specifically used to create a Socket server named ServerSocket. You can use the port number required by the server as a parameter to create a server object.

ServerSocket server = new ServerSocket (9998)

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

Socket incoming = server. accept ()

Then the input stream and output stream are obtained and encapsulated.

BufferedReader in = new BufferedReader (new
InputStreamReader (incoming. getInputStream ()));
PrintWriter out = new PrintWriter (incoming. getOutputStream (), true );

Then, you can use the in. readLine () method to obtain the client input, or use the out. println () method to send data to the client. In this way, different client requests can be responded to according to the program's needs.

The two data streams should be closed after all communication ends. The closing order is to close the output stream first and then the input stream.

Out. close ();
In. close ();
2. Create client code

Compared with the server, the client is simpler. The client only needs to use the ip address of the server and the port of the server as the parameter to create a Socket object. After obtaining this object, you can use the method described in the "Create server" section to achieve 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 creates a Socket object, which is connected to the server object with the IP address 168.160.12.42 and port 9998. An input stream and an output stream are created, which correspond to the output of the server and the write of the client respectively.

3. Create a user interface

You can create your own user interface based on your preferences. This is not the focus of this article.

After the preceding three steps, you can create a simple dialog program. However, the following improvements should be made to improve the program:

1. Currently, the server can only serve one customer, that is, a single thread. It can be improved to a multi-threaded server.

Try
{File: // create 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 ();}

Check whether a customer is connected to the server. If yes, create a Thread to serve the customer. The Thread name is ServerThread, which extends the Thread class, it is written in the same way as the preceding server.

2. In order to get the messages sent by the other party at any time, an independent thread can be created on the server and client to view the input stream. If the input stream has input, it can be instantly displayed. The Code is as follows:

New Thread ()
{
Public void run ()
{
Try
{
While (true)
{
CheckInput ();
Sleep (1000); // detected every 1000 milliseconds
}
} Catch (InterruptedException ex)
{
} Catch (IOException ex)
{
}
}
}. Start ();

The checkInput () method is
Private void checkInput () throws IOException
{
String line;
If (line = in. readLine ())! = Null) file: // checks whether new data exists in the input stream.
T. setPartner (line); file: // display messages in the data stream
}

Through the above improvements, the program can run better.

Appendix: server implementation code

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: // create 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 actionreceivmed (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 is terminated by the other party ");
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: // used to output line content to the user interface
}
}

Related Article

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.