TCP sends receive data
import java.io.IOException;
import Java.io.OutputStream;
import Java.net.Socket;
/*
* TCP protocol to send data:
* A: Create a send-side Socket Object
* This step, if successful, indicates that the connection has been established successfully.
* B: get output stream, write data
* C: Freeing Resources
*
* The connection was rejected. the TCP protocol must look at the server first.
* Java.net.ConnectException:Connectionrefused:connect
*/
Public class Clientdemo {
Public static void main (string[] args)throws IOException {
// Create a send-side Socket Object
//Socket (inetaddress address, int port)
//Socket (String host, int port)
//Socket s = Newsocket (Inetaddress.getbyname ("192.168.12.92"), 8888);
Sockets = newSocket ("219.216.80.19", 8888);
// get output stream, write data
//Public OutputStream Getoutputstream ()
Outputstreamos = S.getoutputstream ();
Os.write ("hello,tcp, here I come ". GetBytes ());
// Freeing Resources
S.close ();
}
}
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;
/*
The *TCP protocol receives data:
* A: Create a Socket object on the receiving end
* B: Listens for client connections. Returns a corresponding socket object
* C: Get input stream, read data display in console
* D: Releasing resources
*/
public class Serverdemo {
publicstatic void Main (string[] args) throws IOException {
Create a socket object on the receiving end
ServerSocket (int port)
SERVERSOCKETSS = new ServerSocket (8888);
Listens for client connections. Returns a corresponding socket object
Public Socket Accept ()
Sockets = Ss.accept (); Listens for and accepts connections to this socket. This method is blocked until the connection is passed in.
Get input stream, read data display in console
Inputstreamis = S.getinputstream ();
Byte[]bys = new byte[1024];
Intlen = Is.read (bys); Blocking method
Stringstr = new String (bys, 0, Len);
STRINGIP = S.getinetaddress (). gethostaddress ();
System.out.println (ip+ "---" + str);
Freeing resources
S.close ();
Ss.close (); This should not be closed.
}
}
TCP Send receive plots:
TCP Send receive data (i)