Introduction to Java Socket network programming
- 2020-04-01 04:14:42
- OfStack
Network application modes mainly include:
Host/terminal mode: centralized computing, centralized management; Client/Server (C/S) mode: distributed computing, distributed management; Browser/server mode: leverage the Internet across platforms.WWW (world wide web) is built on the client/server mode, based on HTML language and HTTP protocol, can provide a variety of Internet services information browsing system. Network information is placed in different locations of the host, the WWW server USES hypertext link to link the information. The WWW client (Brower) is responsible for contacting the server, sending requests to the server, processing HTML hypermedia, providing a graphical user interface (GUI), displaying information, and so on.
In Client/Server mode, on the Server side, you are ready to receive communication from multiple Client computers. For this purpose, in addition to identifying the computer on the Internet with an IP address, a port number is introduced to identify the thread that is being served in the background on the Server side. The combination of port Numbers and IP addresses is called a network socket.
In implementing the C/S pattern in the Java language, sockets fall into two categories:
On the Server side, the ServerSocket class supports the underlying network communication. On the Client side, the Socket class supports the underlying communication of the network.Server machine through the port (bus I/O address) to provide services to the Client machine; The Server machine provides several different services simultaneously on several different ports. The Client accesses a port of the Server, through which the Server is requested to serve it. Provision: port number 0~1023 for system use. For example, the HTTP protocol is at port 80 and the Telnet protocol is at port 23. Ports 1024~65535 are supplied to programs.
When a Client program and a Server program need to communicate, the Socket class can be used to establish Socket connections. A socket connection can be thought of as a phone call: initially the Client program creates the call, and the Server program listens. After the call, either party can speak at any time.
Two sides of the realization of communication streaming socket and datagram socket two optional ways:
Streaming sockets are connected communications, or TCP Control Protocol: a connection is established before each communication and disconnected after the communication. It can guarantee the correctness and reliability of transmission. Datagram socket is connectionless communication, known as the User Datagram Protocol: the data to be transmitted is divided into small packets and sent directly to the Internet. No need to establish and dismantle connections, fast, but no guarantee.
A streaming socket establishes a communication channel between Client and Server programs. Each socket can perform both read and write operations. For either side, the communication session with the other side is:
Establish socket connection, obtain input/output stream, read/write data, close socket after communication.
Using the socket construction method, the client can establish socket objects to the server:
Socket(String host,int port) : host is the IP address of the server, port is the port number, these are pre-agreed.
For example, the code:
try{
Socket mySocket = new Socket( " http://www.weixueyuan.net " ,1860);
}catch(IOException e){}
Then, the getInputStream() method is used to get the input stream, which is used to read the information the server puts into the "line"; Get the output stream with the getOutputStream() method, which writes the information to the line.
The ServerSocket construction method can be used to establish the ServerSocket object that accepts the client socket in the server:
ServerSocket(int port) : specifies the port number to create a ServerSocket object. The port number port should be the same as the port number the client is calling. To do this, use the following code:
try{
ServerSocket serverSocket = new ServerSocket(1860);
}catch(IOException e){}
The server-side program listens on the specified port. When a service request is received from the Client program, a socket object is created to communicate with the Client program corresponding to the port. For example, after executing the above code for creating a serverSocket object and establishing the object serverSocket, it may use the accept() method to get the Socket object and receive information from the Client program from the Socket mySocket. As shown in the following code:
try{
Socket sc = serverSocket.accept();//Ac is a Socket object
}catch(IOException e){}
To undo the service, close the Socket object sc:
sc.close();
Client side application in the C/S pattern. This is a Client side streaming Socket communication simple example, the code illustrates the Client side program writing method. In the example, the Client program makes a request to port 4441 of the host server and completes the read and write to the server after the connection is established.
import java.io.*;
import java.net.*;
public class Client{
public static void main(String args[]){
String s = null;Socket mySocket;
DataInputStream in = null;DataOutputStream out = null;
try{
mySocket = new Socket( " localhost " ,4441);
in = new DataInputStream(mySocket.getInputStream());
out = new DataOutputStream(mySocket.getOutputStream());
out.writeUTF( " good server! " );
while(true){
s = in.readUTF();
if(s==null) break;
else System.out.println(s);
}
mySocket.close();
}catch(IOException e){
System.out.println( " can't connect " );
}
}
}
Server-side application corresponding to the client-side application. The program listens on port 4441, and when it detects a client request, it produces a string that says "client, hello, I'm the server" and outputs it to the client.
import java.io.*;import java.net.*;
public class Server{
public static void main(String args[]){
ServerSocket server = null;
Socket you = null;String s = null;
DataOutputStream out = null;
DataInputStream in = null;
try{
server = new ServerSocket(4441);
}catch(IOException e1){
system.out.println( " ERROR: " +e1);
}
try{
you = server.accept();
in = new DataInputStream(you.getInputStream());
out = new DataOutputStream(you. getOutputStream());
while(true){
s = in.readUTF();
if(s!=null) break;
}
out.writeUTF( "Customer, hello, this is the server." );
out.close();
}
catch(IOException e){System.out.println( " ERROR: " +e);}
}
}
To give full play to a computer's ability to work in parallel, socket connections can be made to a single thread. When a client requests a service from the server, or when the server receives a service request from a client, it starts a thread dedicated to information communication, creates input and output streams in the thread, and completes the communication between the client and the server.
Client applets that put socket connections to work in threads. The interface has a send button, a text box, and a text area. The client application first establishes a socket connection to the server. The data input stream in is used to repeatedly read the information put into the line by the server and display the received information in the text area. When the message is "end", close the socket connection and end the program. The user can also enter information in the text box and press the send message button, then the client program USES the data output stream out to send the contents of the text box to the server.
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
public class Aclient extends Applet implements Runnable,ActionListener{
JButton button; JTextField textF; JTextArea textA;
Socket socket; Thread thread;
DataInputStream in; DataOutputStream out;
public void init(){
setBackground(new Color(120,153,137));
setLayout(new BorderLayout());
Button = new JButton( "Send a message" );
textF = new JTextField(20);
textA = new JTextArea(20,30);
setSize(450,350);
JPanel p = new JPanel();
p.add(textF); p.add(button);
add(textA, " Center " ); add(p, " South " );
button.addActionListener(this);
}
public void start(){
try{
socket = new Socket(this.getCodeBase().getHost(),4441);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e){}
if(thread==null){
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
public void run(){
String s = null;
while(true){
try{
s = in.readUTF();
}catch(IOException e){}
if(s.equals( "The end" )){
try{
socket.close();break;
}catch(IOException e){}
}else texA.append(s + " n " );
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==button){
String s = textF.getText();
if(s! = null){
try{
out.writeUTF(s);
}catch(IOException e1){}
}
else{
try{
out.writeUTF( "Please talk" );
}
catch(IOException e1){}
}
}
}
}
The program establishes a socket connection with the client at the end of 4441. When the server receives the request from the client, it establishes a thread on the client's socket and starts. If there is no customer request, continue to listen to the customer request. The thread creates the input data flow in and output data flow out according to the client's socket. The thread USES in to read the information the client puts into the wire. If the message received is "end", the server closes the socket connection after replying to "end". Otherwise reply: "I am the server you said to me", and the server received the information.
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
public class Aclient extends Applet implements Runnable,ActionListener{
JButton button; JTextField textF; JTextArea textA;
Socket socket; Thread thread;
DataInputStream in; DataOutputStream out;
public void init(){
setBackground(new Color(120,153,137));
setLayout(new BorderLayout());
Button = new JButton( "Send a message" );
textF = new JTextField(20);
textA = new JTextArea(20,30);
setSize(450,350);
JPanel p = new JPanel();
p.add(textF); p.add(button);
add(textA, " Center " ); add(p, " South " );
button.addActionListener(this);
}
public void start(){
try{
socket = new Socket(this.getCodeBase().getHost(),4441);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e){}
if(thread==null){
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
public void run(){
String s = null;
while(true){
try{
s = in.readUTF();
}catch(IOException e){}
if(s.equals( "The end" )){
try{
socket.close();break;
}catch(IOException e){}
}else texA.append(s + " n " );
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==button){
String s = textF.getText();
if(s! = null){
try{
out.writeUTF(s);
}catch(IOException e1){}
}
else{
try{
out.writeUTF( "Please talk" );
}catch(IOException e1){}
}
}
}
}