Network Programming-TCP program instance (only sent data, displayed on the server), network programming-tcp
Package com. yyq; import java. io. IOException; import java. io. outputStream; import java.net. inetAddress; import java.net. socket; import java.net. unknownHostException;/** tcp transmission * 1. tcp is divided into client and server * 2. The client object is socket * server-side pair object is serversocket * // ** client: if the object socket is set up, you can connect to the specified host * Because tcp is connection-oriented, * the server must exist and the connection is successful when the socket service is established, after the channel is formed, data is transmitted through the channel. ** // ** Step: 1. Create a Socket service and specify the host and port to be connected */public class TcpClient {public static void main (String [] args) throws Exception, IOException {// create the socket program of the client and specify the target host and port System. out. println (InetAddress. getLocalHost (); Socket s = new Socket (InetAddress. getLocalHost (), 12345); // if this step succeeds, the path is established, and the socket stream is generated. This allows you to read and write data OutputStream out = s. getOutputStream (); out. write ("tcp ge ". getBytes (); s. close ();}} Package com. yyq; import java. io. IOException; import java. io. inputStream; import java.net. serverSocket; import java.net. socket;/** ing relationship * requirement: Define the endpoint to accept data and print it on the console * server: * 1. create the socket service of the server, serversocket * and listen to a port * 2. obtain the client object linked to the client through the serversocket accept Method * will wait if there is no connection, so this method is congested * and printed on the console * 3. if the client sends data, the server uses the corresponding client object and obtains * The read stream of the object to read the sent data * 4. disable the client (optional) */public class TcpServer {public static void main (St Ring [] args) throws IOException {ServerSocket ss = new ServerSocket (12345); Socket s = ss. accept (); System. out. println (s. getInetAddress (). getHostAddress () + ".... connected "); // The source is the InputStream in = s. getInputStream (); byte [] buf = new byte [1024]; int len = in. read (buf); System. out. println (new String (buf, 0, len); s. close (); // close the client. The server must close the client // ss. close (); close the server }}