Client:
1 PackageWebprogramingdemo;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.io.OutputStream;6 ImportJava.net.Socket;7 Importjava.net.UnknownHostException;8 9 Public classSocketdemo {Ten One /** A * @paramargs - * @throwsIOException - * @throwsunknownhostexception the */ - Public Static voidMain (string[] args)throwsIOException { - -Socket s=NewSocket ("192.168.2.103", 10002); +OutputStream out=S.getoutputstream (); -Out.write ("Java". GetBytes ()); +InputStream is=S.getinputstream (); A bytebuf[]=New byte[1024]; at intlen=Is.read (BUF); -System.out.println (NewString (buf,0, Len)); - s.close (); - } - -}
Service side:
1 PackageWebprogramingdemo;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 ImportJava.io.OutputStream;6 ImportJava.net.ServerSocket;7 ImportJava.net.Socket;8 9 Public classServersocketdemo {Ten One /** A * @paramargs - * @throwsIOException - */ the Public Static voidMain (string[] args)throwsIOException { - -ServerSocket SS =NewServerSocket (10002); -Socket s =ss.accept (); +String IP =s.getinetaddress (). gethostaddress (); -SYSTEM.OUT.PRINTLN (IP + ".... Connected ..."); +InputStream in =S.getinputstream (); A intLen = 0; at byte[] buf =New byte[1024]; -Len =In.read (BUF); -System.out.println (NewString (buf, 0, Len)); -OutputStream os=S.getoutputstream (); -Os.write ("Received". GetBytes ()); - os.close (); in s.close (); - ss.close (); to } + -}
Java Network Programming (TCP protocol-server and client interaction)