The following is a basic example of TCP Java Network programming:
TCP Transport: The idea of client building process:
1, create the TCP client socket service, using the socket object, it is recommended in the process of creation, it is clear that the destination and the host to connect
2, if the connection is established successfully, indicating that the data transmission channel has been established, the channel is the socket I/O flow, is the bottom of the establishment of good, since it is the flow, it is indicated that there is an input stream, there is output stream, in exchange for the socket to get the relevant flow can, getInputStream () and Getoutputstream () of the byte stream.
3, using the output stream, the data output, using the input stream, the data input.
4, close the resources.
TCP Transport: The idea of a server-side build process:
1. Create the socket service on the TCP server by ServerSocket object.
2, the server side provides a port for external, otherwise the client cannot connect.
3. Gets the client object that is connected.
4, through the client object to get the socket stream, read the data sent by the client, and print out
5, close the resources.
The client is as follows:
public class Clientdemo {
public static void Main (string[] args) throws Unknownhostexception, IOException {
1. Create the socket service for the TCP client
Socket socket = new Socket ("192.168.5.163", 10000);
2. Get the output stream of the socket
OutputStream OutputStream =socket.getoutputstream ();
3. Using the output stream to output data
Outputstream.write ("TCP client Demo". GetBytes ());
4. Close Resources
Socket.close ();
}
}
The server side is as follows:
public class Serverdemo {
public static void Main (string[] args) throws IOException {
1. Create a Server object
ServerSocket ss = new ServerSocket (10000);
2. Get the Client object connected
Socket s = ss.accept ();
String IP =s.getinetaddress (). gethostaddress ();
3. Get the input stream through the socket object to get the data sent by the client
InputStream is =s.getinputstream ();
Byte[] buf =new byte[1024];
int len =is.read (BUF);
String teststring =new string (Buf,0,len);
SYSTEM.OUT.PRINTLN (IP + "said: S" + teststring);
S.close ();
Ss.close ();
}
}
Java Network Programming (iii)---Base-level example of TCP