Java socket programming

Source: Internet
Author: User
In fact, a simple understanding of network programming is two Computer It is easier for programmers to master a programming interface and use a programming model. Java The SDK provides some simple APIs to complete these tasks. Work . Socket is one of them. For Java, these APIS exist in the java.net package. Therefore, you only need to import this package to prepare Network Programming.

 

The basic model of network programming is client-to-Server Model. Simply put, two processes communicate with each other, and one of them must provide a fixed location, while the other only needs to know the fixed location and establish a connection between the two. Then complete Data Communication is enough. A fixed location is usually called a server, and a client is usually used to establish a connection. Based on this simple model, you can access network programming.

JAVA supports many APIs for this model. Here I just want to introduce the socket programming interface. Java has simplified socket programming interfaces. First, we will discuss Service How to Establish the program. Java provides serversocket to support it. In fact, when you create a powerful object of this class and provide a port Resource You have created a fixed location for other computers to access you. Serversocket Server = new serversocket (6789); note that port allocation must be unique. Because the port is used to uniquely identify the unique service of each computer. In addition, the port number ranges from 0 ~ The first 65535 ports have been reserved by TCP/IP. Therefore, you can only allocate 1024 ports later than 1024. Now we have a fixed position. All we need is a connection line. This connection line is composed Customer Party first puts forward the request. Therefore, Java also provides a socket object to support it. You only need to create a socket Instance Object for support. Socket Client = new socket (inetaddress. getlocalhost (), 5678); the client must know the IP address of the server. A related class inetaddress is also provided for Java. The instance of this object must be provided through its static method. Its static method mainly provides the method of obtaining the local IP address and directly obtaining the inetaddress through the name or IP address.

Okay. The above method can basically establish a line for the two computers to communicate with each other. But how is data transmitted? In fact, I/O operations are always closely related to network programming. Because the underlying network continues data, unless called remotely, the core of the problem is execution. Otherwise, Data Interaction depends on Io operations. Therefore, you must import the java. Io package. Java Io operations are not complex. It provides readers and writers for byte streams and Unicode, and then provides a buffer for reading and writing data.

Bufferedreader in = new bufferedreader (New inputstreamreader (server. getinputstream ()));
Printwriter out = new printwriter (server. getoutputstream ());

The above two statements are used to create a buffer and convert the original byte stream to Unicode. The original byte stream comes from two methods of socket. Getinputstream () and getoutputstream. Used to obtain the input and output respectively. Now we have basic models and basic operation tools. We can make a simple socket routine.

Service provider:

Import java. Io .*;
Import java.net .*;
Public class myserver {
Public static void main (string [] ARGs) throws ioexception {
Serversocket Server = new serversocket (5678 );
Socket Client = server. Accept ();
Bufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream ()));
Printwriter out = new printwriter (client. getoutputstream ());
While (true ){
String STR = in. Readline ();
System. Out. println (STR );
Out. println ("has receive .");
Out. Flush ();
If (Str. Equals ("end "))
Break;
}
Client. Close ();
}
}

The main purpose of this program is to continuously Receive The information written by the client is only valid. The client will exit the program after sending the "end" string. In addition, the server also responds with "receive. Inform the client that it has received Message .

Client code:

Import java.net .*;
Import java. Io .*;
Public class client {
Static socket server;
Public static void main (string [] ARGs) throws exception {
Servers = new socket (inetaddress. getlocalhost (), 5678 );
Bufferedreader in = new bufferedreader (New inputstreamreader (server. getinputstream ()));
Printwriter out = new printwriter (server. getoutputstream ());
Bufferedreader Wt = new bufferedreader (New inputstreamreader (system. In ));
While (true ){
String STR = wt. Readline ();
Out. println (STR );
Out. Flush ();
If (Str. Equals ("end ")){
Break;
}
System. Out. println (in. Readline ());
}
Server. Close ();
}
}

The client code is Accept Input the customer's keyboard, output the information, and then output "end" for exit identification.

This Program It's just a simple communication between two computers. What if multiple customers access one server at the same time? You can try to run another client and the result will throw an exception. How can we implement multiple clients?

In fact, after a simple analysis, we can see that the customer and Service The main channel for communication is the socket itself. The server agrees to establish communication with the customer through the accept method. In this way, when the customer establishes a socket. The server will also use this link for communication. So long as we have multiple connections. Then our program can be changed to the following:

Server:

 

Import java. Io .*;
Import java.net .*;
Public class myserver {
Public static void main (string [] ARGs) throws ioexception {
Serversocket Server = new serversocket (5678 );
While (true ){
Socket Client = server. Accept ();
Bufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream ()));
Printwriter out = new printwriter (client. getoutputstream ());
While (true ){
String STR = in. Readline ();
System. Out. println (STR );
Out. println ("has receive .");
Out. Flush ();
If (Str. Equals ("end "))
Break;
}
Client. Close ();
}
}
}

 

Here, only an outer while loop is added. The purpose of this loop is to assign a socket to a customer when they come in until the customer completes a interaction with the server. Here, the customer's "end" is accepted" Message . Now, the interaction between multiple customers is realized. But the problem comes again. Although this solution solves multiple customers, it is executed in queue. That is to say, when a customer communicates with the server once, the next customer can come in and interact with the server, and cannot provide services at the same time. So how can we achieve both communication and communication at the same time? Obviously, this is a parallel execution. Problem . So thread is the best solution.

The following question is how to use a thread. The first thing to do is to create a thread and make it Network The connection gets in touch, and then the thread executes the previous operation. To create a thread, either inherit the thread directly or implement the runnable interface, and establish a connection with the socket Contact You only need to pass the reference, and to execute the thread, you must override the run method. What the run method does is what the single-threaded version main just did. So our program becomes like this:

 

Import java.net .*;
Import java. Io .*;
Public class multiuser extends thread {
Private Socket Client;
Public multiuser (socket c ){
This. Client = C;
}
Public void run (){
Try {
Bufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream ()));
Printwriter out = new printwriter (client. getoutputstream ());
// Mutil user but can't parallel
While (true ){
String STR = in. Readline ();
System. Out. println (STR );
Out. println ("has receive .");
Out. Flush ();
If (Str. Equals ("end "))
Break;
}
Client. Close ();
} Catch (ioexception ex ){
} Finally {
}
}
Public static void main (string [] ARGs) throws ioexception {
Serversocket Server = new serversocket (5678 );
While (true ){
// Transfer Location change single user or Multi User
Multiuser mu = new multiuser (server. Accept ());
Mu. Start ();
}
}
}

 

My classes Direct Inherited from the Thread class. In addition, the constructor transmits the reference and establishes a connection with the customer socket. In this way, each thread has a communication pipeline. Similarly, we can enter the run method and hand over the previous operations to the thread for completion. So many Customer The parallel socket is created.

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.