TCP Transport
TCP Socket:ip address and port, socket
Sockets and ServerSocket
Establish client and server side
After the connection is established, the data is transmitted through the IO stream in the socket.
Close socket
Similarly, the client and server side are two separate applications.
TCP Transmission Programming
☆ Basic Ideas (client)
The client needs to specify the IP address and port of the server so that it can try to establish a connection, and if the connection fails, an exception occurs.
The connection is successful, which means that the client and the server have established a channel, then the data can be transmitted through IO stream, and the socket object has provided the input stream and output stream object, which is obtained by getInputStream () and Getoutputstream ().
After the end of the communication with the server, close the socket.
☆ Basic Ideas (server side)
The server needs to be clear on which port it is going to process the data.
When there is client access, to identify which client, you can obtain the connected client object through the Accept (), and through the object and the client through the IO stream data transmission.
When the client access is complete, close the client.
TCP-based socket communication process
TCP Transmission Programming
☆ Client
Establishes the object through the socket and specifies the server-side host and port to connect to.
Socket s = new socket ("192.168.1.1", 9999), outputstream out = S.getoutputstream (); Out.write ("Hello". GetBytes ()); S.close ();
☆ Server Side
Set up a server to listen to a port
ServerSocket ss = new ServerSocket (9999); Socket s = ss.accept (); InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int num = In.read (BUF); String str = new string (buf,0,num); System.out.println (S.getinetaddress (). toString () + ":" +str); S.close (); Ss.close ();
Specific examples:
Client:
Package Cn.hncu.tcp;import Java.io.datainputstream;import Java.io.ioexception;import java.io.inputstream;import Java.io.outputstream;import Java.net.socket;import Java.net.unknownhostexception;public class MyClientSocket { public static void Main (string[] args) {try {socket s = new socket ("192.168.31.168", 8888),//and server three handshake, if failure is abnormal, Otherwise, the socket//sends data outputstream out = S.getoutputstream () out.write ("Hello server!"). GetBytes ());//Receive server response data InputStream in = S.getinputstream ();D atainputstream din = new DataInputStream (in); System.out.println (Din.readutf ()); S.close ();d in.close (); catch (IOException e) {e.printstacktrace ();}}}
Server-side:
Package Cn.hncu.tcp;import Java.io.dataoutputstream;import Java.io.ioexception;import java.io.InputStream;import Java.io.outputstream;import Java.net.serversocket;import Java.net.socket;public class MyServerSocket {public static void Main (string[] args) {try {serversocket server = new ServerSocket (8888); while (true) {System.out.println ("ready to receive a connection ...."); Socket s = server.accept ();//Blocking Method System.out.println ("Receive a connection ....");//read-read data from the client InputStream in = S.getinputstream (); byte buf[] = new Byte[20];in.read (BUF); SYSTEM.OUT.PRINTLN ("Read info:" + new String (BUF));//write--answer client--write data to him outputstream out = S.getoutputstream ();D Ataoutputstream dout = new DataOutputStream (out);d Out.writeutf ("Hello," +s.getinetaddress () + "port#" +s.getport () + "\ Nbye! "); Dout.close (); S.close ();}} catch (IOException e) {e.printstacktrace ();}}}
☆tcp The most likely problem of transmission
The client connects on the service side, both sides are waiting, without any data transfer.
Through routine analysis:
Because the Read method or the ReadLine method is a blocking type.
Workaround:
Custom end Tag
Use the Shutdowninput,shutdownoutput method.
Programming exercises
1. Upload a text file (this example only considers only one client)
Reads a local text file, sends the data to the server side, and stores the data. After the storage is complete, give the client a hint.
Client:
Package Cn.hncu.tcp.upload;import Java.io.bufferedreader;import Java.io.filereader;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.outputstream;import java.io.printwriter;import java.net.Socket; Import Java.net.unknownhostexception;public class Uploadtextclient {public static void main (string[] args) {try {Socket s = new Socket ("192.168.1.106", 10005);//idea: Read the data from the local file and send it out via S.getoutputstream () out object BufferedReader br = new BufferedReader (New FileReader ("Tempfiles\\client.txt")); OutputStream out = S.getoutputstream ();//the output stream here The corresponding server-side input stream PrintWriter pw = new PrintWriter (out, true);//Recommended not to use bufferedwriterstring line = Null;while (line= Br.readline ())!=null) {pw.println (line);} Send end tag to the server---upload end, add end tag, otherwise the server will call read () or ReadLine () when the data is received, or 1:pw.println ("over#[email protected]# @$ ");//cannot appear the end keyword that exists in the file---make a special point//Method 2---it is recommended to use this method---the internal socket to specify the end tag S.shutdownoutput (); Br.close ();// Read the server upload successful feedback message BufferedReader BR2 = new BufferedReader (New InputStreamReader (s.getinputsTream ())); String info = br2.readline (); SYSTEM.OUT.PRINTLN ("Server answer:" +info); S.close (); Br2.close ();} catch (IOException e) {e.printstacktrace ();}}}Server-side:
Package Cn.hncu.tcp.upload;import Java.io.bufferedreader;import Java.io.filewriter;import java.io.IOException; Import Java.io.inputstreamreader;import java.io.printwriter;import java.net.serversocket;import java.net.Socket; public class Uploadtextserver {public static void main (string[] args) {try {serversocket server = new ServerSocket (10005); Socket s = server.accept (); System.out.println (S.getinetaddress (). Gethostaddress () + "... connected");//Read the text file uploaded by the client//source---socket (byte stream)--- Extra: Need to convert to a character stream, cache stream BufferedReader br = new BufferedReader (New InputStreamReader (S.getinputstream ()));//Purpose---hard disk character stream FileWriter---Extra: print stream PrintWriter pw = new PrintWriter (New FileWriter ("Tempfiles\\server.txt"), true); String Line=null;while ((Line=br.readline ())!=null) {//if ("over#[email protected]#@$". Equals (line)) {//break ;//}pw.println (line);} Pw.close ();//upload succeeded, give the client a hint message printwriter pw2 = new PrintWriter (S.getoutputstream (), True);p w2.println ("Upload succeeded!"); S.close (); Server.close ();p w2.close ();} catch (IOException e) {e.Printstacktrace ();}}}
2, upload the picture file (this case consider a number of clients)
Client requirements: Send a picture file to the server and read the feedback information. Ask to determine if the file exists and whether the format is JPG or GIF and requires the file to be less than 2M.
Service-side requirements: Receive the image data sent by the client. After storing, give back an upload success word. Supports concurrent access for multiple users.
Client:
Package Cn.hncu.tcp.upload;import Java.io.file;import Java.io.fileinputstream;import java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.net.socket;import java.net.UnknownHostException; public class Uploadpicclient {public static void main (string[] args) {//Health condition if (args.length!=1) {System.out.println (" Please specify the file "); return;} File File = new file (Args[0]); File.exists () && file.isfile ()) {System.out.println ("The uploaded file does not exist"); return;} if (! ( File.getname (). EndsWith (". jpg") | | File.getname (). EndsWith (". gif")) {System.out.println ("file name extension must be JPG or gif"); return;} if (File.length () >=1024*1024*2) {System.out.println ("file too large, should not exceed 2M, please re-upload!") "); return;} Upload try {Socket s = new socket ("127.0.0.1", 9999); FileInputStream fin = new FileInputStream (file); OutputStream out = S.getoutputstream (); byte buf[] = new Byte[1024];int len =0;while ((Len=fin.read (BUF))!=-1) {out.write (buf, 0, Len);} S.shutdownoutput ();//Tell the server that the file has been uploaded//read the server's feedback InputStream in = S.getinputstream (); byte buf2[] = newByte[1024];int len2 = In.read (BUF2); String info = new string (BUF2,0,LEN2); SYSTEM.OUT.PRINTLN (info);//Off-stream fin.close (); S.close ();} catch (IOException e) {e.printstacktrace ();}}}Server-side:
Package Cn.hncu.tcp.upload;import Java.io.file;import Java.io.fileoutputstream;import java.io.IOException;import Java.io.inputstream;import Java.io.outputstream;import Java.net.serversocket;import Java.net.Socket;public class uploadpicserver {public static void main (string[] args) {try {serversocket server = new ServerSocket (9999), while (true) {so Cket s = server.accept ();//is only responsible for the handshake with the client new Thread (new Uploadthread (s)). Start (); Server.close ();} catch (IOException e) {e.printstacktrace ();}}} Class Uploadthread implements Runnable{private socket S;public Uploadthread (socket s) {THIS.S = s;} @Overridepublic void Run () {String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected"); try {inputstream in = S.getinputstream (); File dir = new file ("D:\\mypic"), if (!dir.exists ()) {Dir.mkdir ();} int count=1; File File = new file (dir,ip+ ". jpg"), while (File.exists ()) {file = new file (dir,ip+ "(" + (count++) + ")" + ". jpg");//file name with number} FileOutputStream fout = new FileOutputStream (file);//from the socket streamThe data is read in and stored to a local file. Equivalent to copy byte buf[] = new Byte[1024];int Len=0;while ((Len=in.read (BUF))!=-1) {fout.write (buf, 0, Len);} Picture received//Send feedback to client outputstream out = S.getoutputstream (); Out.write ("Upload succeeded". GetBytes ()); Fout.close (); S.close ();} catch (IOException e) {e.printstacktrace ();}}}
Java------Socket Series (quad) TCP