Client code:
Packagecom.kaige123.net01;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket;ImportJava.net.UnknownHostException;/*** Edith * / Public class Client {Public static void main(string[] args) throws Exception {//If the other server does not exist, it will errorSocket socket =NewSocket ("127.0.0.1",8080); InputStream input = Socket.getinputstream (); OutputStream output = Socket.getoutputstream (); Output.write ("Hello server, I am Kay, do you remember me?" ". GetBytes ()); Output.flush ();//Quickly export the content to the other side byte[] b=New byte[1024x768];intLen=input.read (b); System.out.println ("The server said:"+NewString (b,0, Len)); Output.close (); Input.close (); Socket.close ();}}
Service-Side code:
Packagecom.kaige123.net01;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** Edith * / Public class Server {Public static void main(string[] args) throws Exception{//If all is occupied then it will throw an exception //Establish good one server monitor 8080 portServerSocket Server =NewServerSocket (8080);//wait for the client to connect to the serverSocket socket = server.accept ();//code to run to this sentence will jam the main blocked waitInputStream input = Socket.getinputstream (); OutputStream output = Socket.getoutputstream ();byte[] B =New byte[1024x768*5];intLen = Input.read (b); String s =NewString (b,0, Len); System.out.println (s); s ="Hello Edith, I am back from Dongguan beautiful!"; Output.write (S.getbytes ()); Output.close (); Input.close (); Socket.close ();}}
TCP Simple Communication