1 PackageCom.yyq;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.io.OutputStream;6 Importjava.net.InetAddress;7 ImportJava.net.Socket;8 9 Ten /* One * Demonstrate TCP's transfer of client and server visits A * Requirements: The client sends data to the server to send back the data to the client after retrieving the information. - */ - /* the * Client - * 1. Set up the socket service. Specify the host and port to receive - * 2. Get the output stream in the socket stream, write the data to the six, send it over the network to the server - * 3. Gets the input stream in the socket stream, obtains the data from the service-side feedback, and prints + * 4. Close the client resource. - * + */ A Public classTcpClient2 { at Public Static voidMain (string[] args)throwsException { -Socket s =NewSocket (Inetaddress.getlocalhost (), 4321); -OutputStream out =S.getoutputstream (); -Out.write ("Hello, service side". GetBytes ()); -InputStream in =S.getinputstream (); - byte[] buf =New byte[1024]; in intLen =In.read (BUF); -System.out.println (NewString (buf,0, Len)); to } + } - the * PackageCom.yyq; $ Panax Notoginseng Importjava.io.IOException; - ImportJava.io.InputStream; the ImportJava.io.OutputStream; + ImportJava.net.ServerSocket; A ImportJava.net.Socket; the + Public classTcpServer2 { - Public Static voidMain (string[] args)throwsException { $ServerSocket SS =NewServerSocket (4321); $Socket s =ss.accept (); -InputStream in =S.getinputstream (); - byte[] buf =New byte[1024]; the intLen =In.read (BUF); -System.out.println ("IP:" +s.getinetaddress (). gethostaddress ());WuyiSystem.out.println (NewString (buf,0, Len)); theOutputStream out =S.getoutputstream (); -Thread.Sleep (10000); WuOut.write ("You're good too."). GetBytes ()); - } About}
Network Programming-TCP Program instance (client end Heserver communication)