Java Learning Socket Programming

Source: Internet
Author: User

What is a socket

Socket programming in Java is actually network programming, usually using TCP/IP protocol-based socket programming. All the APIs for socket programming are in the java.net package, which typically enables communication between the client and server side.

The process of socket communication

Server side Listen (listening) a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept message to the client side. A connection is built up. Both the server side and client side can communicate with each other through methods such as Send,write.

For a full-featured socket, the following basic structure is included, and the work process consists of the following four basic steps:

    1. Create sockets;
    2. Open the input/output stream connected to the socket;
    3. Read/write the socket according to a certain protocol;
    4. Close the socket. Socket programming requires that the location of the server must be fixed,
      1
      ServerSocket server=New ServerSocket (6789);

Note: The allocation of the port number must be unique, because the port is to uniquely identify the unique service for each computer. In addition, the port number is from 0 to 65535, the first 1024 ports have been TCP/IP as a reserved port, so you can only allocate ports after 1024.

1
Socket socket = server.accept ();

Note: The Accept method is a blocking method that waits for blocking until a connection is established between the server side and the client.

In the client, open a socket with the following code:

1
New Socket (//two parameters (Host,port)

Note: Host is the machine that the client needs to connect to, and port is the one that the server uses to listen for requests.

Example:

We get the OutputStream object from the client socket object and then write the data. Very similar to file IO processing code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PublicClassClientsocket {
PublicStaticvoidmain (String args[]) {
String host = "127.0.0.1";
int port = "8919";
try{
Socket client = new Socket (host, Port);
writer writer = new outputstreamwriter (Client.getoutputstream ());
Writer.writer ( Writer.flush ();
Writer.close ();
Client.close ();
} catch (IOException e) {
E.printstacktrace ();
}
/span>

Create a socket on the server side,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
PublicClassserverclient {
PublicStaticvoidMain(string[] args) {
int port =8919;
try {
ServerSocket Server =New ServerSocket (port);
Socket socket = server.accept ();
Reader reader =New InputStreamReader (Socket.getinputstream ());
Char chars[] =Newchar[1024];
int len;
StringBuilder builder = new StringBuilder ();
while ((Len=reader.read (chars))! =-1) {
Builder.append (new String (chars, 0, Len));
Reader.close ();
Socket.close ();
Server.close ();
catch (Exception e) {
E.printstacktrace ();
}
/span>

Client/server programs that support multiple clients

The previous Client/server program can only implement a conversation between the server and a client. In practice, it is often a permanent program running on the server that can receive requests from multiple clients and provide the appropriate services. In order to realize the function of serving multiple customers in the server side, the above program needs to be reformed and multi-client mechanism can be realized by multithreading. The server always listens for customer requests on the specified port, and once it listens to a customer request, the server initiates a dedicated service thread to respond to the customer's request, and the server itself enters the listening state immediately after the thread is started, waiting for the next customer to arrive.

Java Learning Socket Programming

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.