Use of sockets in Java
Client Side
Package Org.tizen.test;import Java.io.ioexception;import Java.io.outputstream;import java.net.inetaddress;import Java.net.socket;import Java.net.sockettimeoutexception;public class Testsocket {public static void main (String []str) { OutputStream OS = null; Socket socket = null;try {//1. The object that created the socket, indicating the IP address of the server by the constructor, and the port number received socket = new socket (Inetaddress.getbyname (" 192.168.1.104 "), 9000);//2.getoutputstream send data, return Outputstreamos = Socket.getoutputstream ()//3. Specific output process Os.write (" 1111111111 1111111111 ". GetBytes ());} catch (Exception e) {//Todo:handle exception}finally{//4. Close the specific stream and Socketif (os!=null) {try {os.close ();} catch ( IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (socket!=null) {try {socket.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}}
Server Side
Package Org.tizen.test;import Java.io.ioexception;import Java.io.inputstream;import java.net.serversocket;import Java.net.socket;public class Testtcpip {public static void main (String []str) {ServerSocket SS = null; Socket s = null;inputstream is = null;try {//1. Creates a Socketserver object, indicating its own port SS = new ServerSocket (9000) via the constructor;//2. Calling sockets Erver The Accept method, returns a socket object s = ss.accept ();//3. Calling the getinputstream of the socket object gets the stream that the client sent over is = S.getinputstream (); byte[] B = new Byte[20];int len; while (len = Is.read (b))!=-1) {string str1 = new String (B,0,len); System.out.println (STR1);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Day20 Java Socket Usage