Client
/******************** Client **************************/public void Startsocket () {New Thread (new Initsocket ()). Star T ();} Private Socket sendclient = null;private OutputStream Sendoutstream = null;private Boolean bsendisc = False;class initSock ET implements Runnable {@Override public void run () {try {sendclient = new Socket (); Inetsocketaddress isa = new Inetsocketaddress ("127.0.0.1". Replace ("/", ""), 8088); Sendclient.connect (ISA, 2000); Sendclient.setsendbuffersize (500000); Sendclient.setreceivebuffersize (500000); Sendclient.setperformancepreferences (0, 0, 1); Bsendisc = sendclient.isconnected (); Sendclient.settcpnodelay (TRUE); Sendclient.setkeepalive (TRUE); Sendoutstream = Sendclient.getoutputstream (); } catch (IOException e) {e.printstacktrace (); }}//After the connection is established, the data is sent using the OutputStream sendoutstream.write; BYTE stream data
Note: In Android, the socket connection operation cannot be performed in the main thread, and a new thread must be opened;
Service side
/******************** Server **************************/public void Startlisten () { new Thread (this). Start ();} Private final int PORT = 8088;private serversocket server;public void Run () {//Create TCP server receive video stream socket CLIENT;DATAINPUTST Ream is = null;try { Server = new ServerSocket (PORT); Client = Server.accept (); Client.setreceivebuffersize (500000); Client.setsendbuffersize (500000); Client.settcpnodelay (true); Client.setperformancepreferences (0, 0, 1); is = new DataInputStream (Client.getinputstream ());} catch (IOException e) { e.printstacktrace ();} Start reading byte[] data = new byte[1000] After establishing the connection; int length = is.read (data); Reads the data in the socket, saves it in data, and returns the length of the read}
Java--Use of TCP sockets