Java Socket learning notes

Source: Internet
Author: User

I recently learned something about Java Socket. I found a lot of code references from my friends on the Internet and made two small examples for data use.

I. Two main problems in network programming:

One is how to accurately locate one or more hosts on the network, and the other is how to transmit data reliably and efficiently after finding the hosts.
In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet.
The TCP layer provides an application-oriented reliable (TCP) or non-reliable (UDP) data transmission mechanism, which is the main object of network programming, generally, you do not need to care about how the IP layer processes data.

Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer submits an application to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, so that later customers can get services in a timely manner.

2. Two types of transmission protocols: TCP and UDP:

TCP is short for tranfer control protocol. It is a connection-oriented protocol that ensures reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.

UDP is short for user datasync protocol. It is a connectionless protocol. Each datagram is an independent information, including the complete source address or destination address, it is transmitted to the destination in any possible path on the network. Therefore, the correctness of the arrival time, arrival time, and content cannot be guaranteed.

UDP:

1. Complete address information is provided in each datagram, so there is no need to establish a connection between the sender and the receiver.

2. There is a limit on the size of UDP data transmission. Each transmitted datagram must be within 64 KB.

3. UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order.

TCP:

1. For connection-oriented protocols, a connection must be established before data transmission between sockets. Therefore, the connection time is required in TCP.

2. TCP transmission data size limit. Once the connection is established, the sockets of both parties can transmit big data in a unified format.

3. TCP is a reliable protocol that ensures that the receiver fully and correctly obtains all data sent by the sender.

Java Socket:

The so-called socket is also called "socket". It is used to describe the IP address and port and is a communication chain handle. Applications usually send requests to or respond to network requests through "Sockets.

Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A socket is uniquely identified by an IP address and a port number.

However, the Protocol types supported by the socket are not only TCP/IP, so there is no necessary link between the two. In the Java environment, socket programming mainly refers to network programming based on TCP/IP protocol.

Socket communication process:

Server listen (listener) whether a port has a connection request. The client sends a connect (connection) request to the server, and the server sends an accept (accept) message back to the client. A connection is established. Both the server and client can communicate with each other by sending, writing, and other methods.

Generally, socket communication involves four steps:

1. Create a socket.

2. Open the input/output stream connected to the socket.

3. Perform read/write operations on the socket according to certain protocols.

4. Disable socket. (display close is not used in practical applications. Although this is recommended in many articles, in my program, it may be because the program itself is relatively simple and has low requirements, so there is no impact.

The following are two examples: one is single-threaded socket communication and the other is multi-threaded socket communication.

Single thread:

Package COM. zyujie. socket; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. serversocket; import java.net. socket; public class serverapp {public static void main (string [] ARGs) throws ioexception {// create a server, listen to port 6688, and the port number is from 0 ~ Between 65535, the socket port is preferably over 1024. The port earlier than 1024 has been reserved by TCP/IP as serversocket Server = new serversocket (6688); // receives a connection, and return the socket object instance Socket Client = server of a client. accept (); // The original byte stream comes from two methods of socket. getinputstream () and getoutputstream () // here we create a buffer to convert the original byte stream to unicodebufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream (); printwriter out = new printwriter (client. getoutputstream (); While (true) {// read client messages in one row string STR = in. readline (); system. out. println (STR); // return the message to the client. println ("the server has received the message... "); out. flush (); // The server end ends socket communication after reading the end, and the listener exits if (Str. equals ("end") {break ;}// socket instance, Connection closed client. close ();}}

 

Package COM. zyujie. socket; import Java. io. bufferedreader; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. inetaddress; import java.net. socket; public class clientapp {Private Static socket server; public static void main (string [] ARGs) throws exception {// inetaddress is a class in the java.net package, the static method is to obtain the IP address of the Local Machine and directly obtain the inetaddress through the name or IP. Server = new socket (inetaddress. getlocalhost (), 6688); bufferedreader in = new bufferedreader (New inputstreamreader (server. getinputstream (); printwriter out = new printwriter (server. getoutputstream (); // console input string bufferedreader Wt = new bufferedreader (New inputstreamreader (system. in); While (true) {// The input string STR = wt in the console for reading a row. readline (); // send it to the server end out. println (STR); out. flush (); If (Str. equals ("end") {break;} // reads the message system returned by the server. out. println (in. readline ();} // socket instance, Connection closed server. close ();}}

Multi-threaded socket communication only provides server code, which is the same as that of a single thread:

Package COM. zyujie. socket; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. serversocket; import java.net. socket; public class socketserver extends thread {private Socket Client;/** constructor that receives each socket instance */Public socketserver (Socket socket) {This. client = socket;}/** thread execution Method */Public void run () {try {// here we create a buffer for input and output, convert the original byte stream to unicodebufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream (); printwriter out = new printwriter (client. getoutputstream (); While (true) {// read client message string STR = in. readline (); system. out. println (STR); // return the message to the client out. println ("the server has received the message... "); out. flush (); // The end ends when an end is encountered. Here, only the connection from a single client is ended if (Str. equals ("end") {break ;}// socket instance, Connection closed client. close ();} catch (ioexception ex) {} finally {}}/** enable the thread method to connect multiple users to the socket server. */public static void main (string [] ARGs) throws ioexception {// create a server and listen to port 6688 serversocket Server = new serversocket (6688 ); // use the server to maintain the permanent listening status while (true) {// receives connections from each client and returns the socket instance socketserver Ss = new socketserver (server. accept (); // starts a thread for each client to perform operations on the SS. start ();}}}

 

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.