A client can usually use the socket's constructor to connect to a specified server, which typically uses the following two constructors.
Socket (lnetaddress/string remoteaddress, int port): Creates a socket connected to the specified remote host, remote port, which does not specify a local address, a local port, and defaults to the default IP address of the local host. The default is to use the system dynamically specified IP address.
Socket (lnetaddress/string remoteaddress, int port, lnetaddress localaddr, int localport): Creates a socket connected to the specified remote host, remote port, and refers to The native IP address and local port number for situations where the local host has multiple IP addresses.
The remote host specified in the above two constructors can be specified using either lnetaddress or directly using a string object, but the program typically uses a string object (such as 192.168.2.23) to specify the remote IP. Using the first method is simpler when the local host has only one IP address. As shown in the following code:
Create a socket connected to a native, 30000 port
Socket s = new socket ("172.18.5.198", 30000);
You can use the socket to communicate.
......
When the program executes the above code, the code will connect to the specified server, allowing the server's ServerSocket accept () method to execute down, so that the server side and the client produce a pair of interconnected sockets.
When the client, the server side generated the corresponding socket, the program does not need to sub-servers, clients, but through the respective sockets to communicate. The socket provides the following two ways to get the input stream and output stream:
InputStream getInputStream (): Returns the input stream corresponding to the socket object, allowing the program to extract data from the socket through the input stream.
Onputstream Getonputstream (): Returns the output stream corresponding to the socket object, allowing the program to flow through this output to the socket for output data.
By the two methods returned by the InputStream and OutputStream, can be drawn: no matter what the underlying IO stream is the node flow, file flow, network socket generated by the flow, the program can be packaged into a processing stream, so as to provide more convenient processing.
The following is an example of a simplest network communication program that describes TCP protocol-based network communication:
The following server program needs to run on the PC, it only establishes serversocket monitoring and uses the socket to get output stream output.
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;
public class Simpleserver {
public static void Main (string[] args) throws IOException {
Create a ServerSocket to listen for connection requests from the client socket
ServerSocket ss = new ServerSocket (30000);
Using loops to continuously accept requests from clients
while (true) {
Whenever a client socket request is received, the server side also generates a socket
Socket s = ss.accept ();
OutputStream OS = S.getoutputstream ();
Os.write ("Hello! You received a new year greeting from the server: \ n ". GetBytes (" Utf-8 "));
Turn off the output stream and close the socket
Os.close ();
S.close ();
}
}
}
The above program set up a ServerSocket object, the ServerSocket on 30000 port listening, the serversocket will be listening, waiting for the client program connection, the next code for the program to open the socket corresponding output stream, and writes a string of data to the output stream.
The above program does not wrap the OutputStream stream into PrintStream, and then uses PrintStream to output the entire string directly, because the server-side program runs on the Windows host. When using the PrintStream output string directly, the system platform's string (that is, GBK) is encoded by default, but the client of the program is an Android application running on the Linux platform (Android is the Linux kernel), Therefore, when the client reads the network data by default using the UTF-8 character set to decode, this is bound to cause garbled, in order to ensure that the client can parse the data correctly, here manually control the encoding of the string, forcibly specified using the UTF-8 character set encoding, so that the garbled problem can be avoided.
The next client will only use the socket to establish a connection to the specified IP, the specified port, and use the socket to get the input stream to read the data, the client program is an Android app, so you still need to build an Android project, the program's interface contains a text box, Used to display string data read from the server side.
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.net.Socket;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.widget.EditText;
public class SimpleClient extends Activity {
EditText Show;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_simple_client);
Show = (EditText) Findviewbyid (r.id.show);
Close the input stream, socket
try {
Socket socket = new Socket ("172.18.5.88", 30000);
Wraps the input stream corresponding to the socket into a bufferreader
BufferedReader br = new BufferedReader (
New InputStreamReader (Socket.getinputstream ()));
Perform normal IO operations
String line = Br.readline ();
Show.settext ("Data from the server" +line);
Br.close ();
Socket.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}
}
The above program uses ServerSocket and socket to establish a network connection, then the socket to get the input stream, output stream to communicate. It is not difficult to see, once using serversocket, socket to establish a network connection, the program through the network communication and ordinary IO is not much different.
The Android app requires access to the Internet, so you also need to give the app access to the Internet, which is to add the following configuration snippet to the Androidmanifest.xml file:
<!--authorized access to the Internet--
<uses-permission android:name= "Android.permission.INTERNET"/>
First run the Simpleserver class in the above program, you will see the server has been waiting, because the server used a dead loop to receive requests from the client, and then run the client Androidclient class, you will see the program output: "Data from the server: Hello, You received a new year greeting from the server! "This indicates that the client and server communication succeeded.
In practice, the program may not want to make the network connection, read the server data of the process has been blocked, but hope that when the network connection, read operations beyond a reasonable time, the system automatically considers that the operation failed, this reasonable time is the time-out. The socket object provides a setsotimeout (int timeout) to set the timeout length, as in the following code:
Socket s = new socket ("127.0.0.1", 30000);
Timeout is considered after 10 seconds of setting
S.setsotimeout (10000);
After specifying the timeout length for the socket object, if the time limit has been exceeded before the read and write operations are done using the socket, these methods will throw a Sockettimeoutexception exception and the program can catch the exception and handle it appropriately. such as the following code:
try {
Using scanner to read data from the network input stream
Scanner scan = new Scanner (S.getinputstream ());
Reads a line of characters
String line = Scan.nextline ();
}
Catching sockettimeoutexception Exceptions
catch (Sockettimeoutexception e) {
To handle an exception
......
}
Suppose the program needs to specify a timeout length when connecting to the server for the socket: that is, after a specified time, if the socket is not connected to the remote server, the socket connection is considered timed out. However, the parameters of the specified timeout length are not available in all the constructors of the socket, so the program should first create a disconnected socket and then call the socket's connect () method to connect to the remote server, and the Connect method can accept a timeout parameter. such as the following code:
Create a non-connected socket
Socket s = new socket ();
Connect the socket to a remote server and consider the connection timed out if it has not been connected for 10 seconds
S.connect (New InetAddress (Host,port), 1000);
Using the socket for communication