TCP, UDP practice (UDP chat programs, TCP upload text files and picture files)

Source: Internet
Author: User

TCP, UDP programming exercises


TCP☆ Upload text file

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.

first, the idea of solving problems

Client: (1) Create socket object----with server ip+ port number

(2) read the contents of the file

(3) through the socket to send the content to the server side (the socket in the output stream packaging "print stream" for sending text, is a more secure output mode, no distortion.) )


Server-side: (1) Create server socket---serversocket

(2) Get the client socket via ServerSocket

(3) Through the client socket, read the data sent to each other, and write this data into a new file


ii. annotations and implementation codes

Uploadtextclient.java class

Package Net.tcp.textfileupload;import Java.io.bufferedreader;import Java.io.filereader;import java.io.IOException; Import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.socket;import Java.net.unknownhostexception;public class Uploadtextclient {public static void main (string[] args) {try {//1 Create a Socket object----with the server's ip+ port number socket s = new socket ("127.0.0.1", 10000),//2 reads the contents of the file//3 sends the content to the server side via the socket (the output stream in the socket is packaged as " Print Flow "To send text, is a more secure way to output, without distortion. ) BufferedReader bufr = new BufferedReader (New FileReader ("Tempfile\\client.txt")); PrintWriter out = new PrintWriter (S.getoutputstream (), true);//Send string line = Null;while ((Line=bufr.readline ())!=null ) {out.println (line);} 6 Send an end tag to the server//out.println ("%$#@88# #K # #");//Send custom end tag s.shutdownoutput ();//5 read server-side feedback s.getinputstream () BufferedReader BUFR2 = new BufferedReader (New InputStreamReader (S.getinputstream ())); String text = Bufr2.readline (); SYSTEM.OUT.PRINTLN ("server:" +text);//4 off-stream bufr.close (); Out.close (); S.close ();} Catch(Unknownhostexception e) {E.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}

Uploadtextserver.java class

Package Net.tcp.textfileupload;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 {//1 create server socket---serversocketserversocket SE RVer = new ServerSocket (10000);//2 through ServerSocket obtains the client's socketsocket s = server.accept ();//3 through the client socket, read the data sent by the other side, and write this data into a new file//Source: Socket-->s.getinputstream ()-->bufferedreader Purpose: FileWriter ("Tempfile\\server.txt")-- > can be packaged as printwriter for output bufferedreader bufr = new BufferedReader (New InputStreamReader (S.getinputstream ())); PrintWriter pw = new PrintWriter (New FileWriter ("Tempfile\\server.txt"), true); String line = Null;while ((Line=bufr.readline ())!=null) {//if ("%$#@88# #K # #". Equals (line)) {//break;//}pw.println ( line);} 5 Send feedback to the client via the client socket to send string str = S.getinetaddress (). GetHostName (); str = str + "::: File uploaded successfully ..."; PrintWriter out = new PrintWriter (S.getoutputstream (), True), Out.println (str),//4 off-stream bufr.close ();p w.close (); S.close (); server.close ();} catch (IOException e) {e.printstacktrace ();}}}



☆ Upload image file

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.

first, the idea of solving problems

Client: (1) Determine if the file output file exists: file.exists () && file.isfile ()

(2) Determine file format problem: File.getname (). EndsWith (". jpg") | | File.getname (). EndsWith (". gif")

(3) file less than 2m:file.length () >=1024*1024*2

(4) Then read out the file data via IO and send it to the server via the socket

Note: After the file is sent, remember to send an end sign S.shutdownoutput (), this sentence is very important Oh!!!


Server-side: mainly to solve the problem of how the server side handles when multiple clients are transferring pictures to the server at the same time. method is resolved by a new thread. Whenever there is a client request, a new line

Process to communicate with each other, this has to do with the benefits of meeting each client at the same time and a server to communicate multiple times.

ii. annotations and implementation codes

Uploadpicclient.java class

Package Net.tcp.picfileupload;import Java.io.file;import Java.io.fileinputstream;import java.io.InputStream;import Java.io.outputstream;import Java.net.socket;public class Uploadpicclient {public static void main (string[] args) throws exception{//condition, anti-logic if (args.length!=1) {System.out.println ("please specify filename"); 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 extension must be jpg or gif!"); return;} if (File.length () >=1024*1024*2) {System.out.println ("file is too large, must be less than 2M, please re-select ..."); return; Socket s = new socket ("127.0.0.1", 10002); FileInputStream fis = new FileInputStream (file); OutputStream out = S.getoutputstream (); byte buf[] = new Byte[1024];int len =0;while ((Len=fis.read (BUF))!=-1) {out.write (buf, 0, Len);} S.shutdownoutput ();//Send end tag//read feedback from server InputStream in = S.getinputstream (); byte b[] = new Byte[1024];int Len2 = In.read ( b); String info = new StRing (B,0,LEN2); SYSTEM.OUT.PRINTLN (info); Fis.close (); Out.close (); S.close ();}}
Uploadpicserver.java class

Package Net.tcp.picfileupload;import Java.io.file;import Java.io.filenotfoundexception;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) Throws Exception{serversocket Server = new ServerSocket (10002), while (true) {Socket s = server.accept (); New Thread (New UPL Oadthread (s)). Start ();}} Class Uploadthread implements Runnable{private socket s = null;public uploadthread (socket s) {THIS.S = s;} @Overridepublic void Run () {String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ ".... connected!"); /Receive data from the client (picture file) file dir= new file ("C:\\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");} try {fileoutputstream fos = new FileOutputStream (file); byte buf[] = new Byte[1024];int Len=0;inputstream in = S.getinputstream (); while ((Len=in.read (BUF))!=-1) {fos.write (buf, 0, Len);} OutputStream out = S.getoutputstream (); Out.write (ip+ "-The picture data has been uploaded successfully!"). GetBytes ());//Flow Out.close (); Fos.close (); S.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}}
Note A small problem: it is not possible to run the client program (Uploadpicclient.java) directly.

To do this: Right-click on the main method, select Run as---> Run configurations--->arguments--->program Arguments fill in the absolute path of the file to be transferred, That is, the path plus

Name of the item.


When the client and the server to transmit data, the sending and receiving end of the flow must correspond.



UDP☆udp Chat Program

A, through the keyboard input to get the information to send.

b, the send and receive are encapsulated in two threads respectively.

first, the idea of solving problems

Because it is a chat program, so it is two client communication, so as long as a client can be written, the other only need to change the sender and receiver port.

Each client has a sent Datagramsocket and a received Datagramsocket, which is then started by one thread, respectively. This guarantees that each client can remain in the receiving and sending State until the end prompt is received.

ii. annotations and implementation codes

Udpchat.java class

Package Net.udp.updchat;//111111import Java.net.datagramsocket;import Java.net.socketexception;public class UDPChat {public static void main (string[] args) {try {datagramsocket send = new Datagramsocket (10003);//Send Port Datagramsocket receiv E = new Datagramsocket (10004);//Receive Port new thread (new Send). Start (); New thread (new receive). Start (); catch (SocketException e) {e.printstacktrace ();}}}

Receive.java class

Package Net.udp.updchat;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket; public class Receive implements Runnable {Datagramsocket ds=null;public receive (Datagramsocket ds) {this.ds = ds;} @Overridepublic void Run () {try {byte buf[] = new Byte[1024];while (true) {Datagrampacket DP = new Datagrampacket (buf, BUF.L Ength);d s.receive (DP); String IP = dp.getaddress (). gethostaddress (); int port = Dp.getport (); String str = new String (Dp.getdata (), 0,dp.getlength ()); System.out.println (ip+ ":" +port+ "==>" +str), if ("over". Equalsignorecase (str)) {System.out.println (ip+ "Leave the chat room ....) ");}}} catch (IOException e) {e.printstacktrace ();}}}

Send.java class

Package Net.udp.updchat;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStreamReader; Import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;public class Send Implements Runnable {Datagramsocket ds=null;public Send (datagramsocket ds) {this.ds = ds;} @Overridepublic void Run () {try {BufferedReader bufr = new BufferedReader (new InputStreamReader (system.in)); String Line=null, while ((Line= bufr.readline ())!=null) {byte buf[] = Line.getbytes ();D Atagrampacket DP = new Datagrampacket (buf, Buf.length, Inetaddress.getbyname ("192.168.31.115"), 10002);//(10002) Same as the receive port of another client Ds.send (DP if ("Over". Equalsignorecase (line)) {break;}} Ds.close ();} catch (IOException e) {e.printstacktrace ();}}}









Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP, UDP practice (UDP chat programs, TCP upload text files and picture files)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.