Big summary of Socket programming

Source: Internet
Author: User
Tags closing tag


1.UDP No connection Chat

/* Write a chat program. There is part of the data collected, and the part that sends the data. These two parts need to be executed at the same time. Then you need to use multithreaded technology. A thread control to receive, a line programmed to send. Because the receive and send action is inconsistent, define two run methods. And the two methods are encapsulated into different classes. */import java.io.*;import java.net.*;class send implements runnable{private  Datagramsocket ds;public send (datagramsocket ds) {this.ds = ds;} Public 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 ("127.0.0.1"), 10002); System.out.println (Inetaddress.getbyname ("127.0.0.1"));d S.send (DP), if ("886". Equals (line) is break;}} catch  (exception e) {throw new runtimeexception ("Send side Failed");}}} Class rece implements runnable{private datagramsocket ds;public rece ( DATAGRAMSOCKET DS) {this.ds = ds;} public Void run () {Try{while (true) {byte[] buf = new byte[1024];D atagrampacket dp =  new datagrampacket (buf,buf.length);d s.receive (DP); String ip = dp.getaddress (). gethostaddress (); String data = new string (Dp.getdata (), 0,dp.getlength ()), if ("886". Equals (data)) { System.out.println (ip+ ".... Leave the chat room "); System.out.println (ip+ ":" +data);}} catch  (exception e) {throw new runtimeexception ("Receive Side Failed");}}} Class  chatdemo{public static void main (String[] args)  throws  Exception{datagramsocket sendsocket = new datagramsocket ();D Atagramsocket recesocket  = new datagramsocket (10002); New thread (New send (Sendsocket)). Start (); New Thread (New rece (Recesocket)). Start ();}}



2.TCP Uppercase Conversion Server

/* Requirements: Create a text conversion server. The client sends text to the server, and the service order converts the text to uppercase in return to the client. And the customer degree can continue to do text conversion. When the client enters over, the conversion ends. Analysis: The client: Since it is manipulating the data on the device, you can use IO technology and think according to the operational rules of IO. Source: Keyboard entry. Purpose: Network device, network output stream. It also operates on text data. You can select a character stream. Step 1, set up the service. 2, get keyboard entry. 3. Send the data to the server. 4, then go back to the server to return the uppercase data. 5, end, close resources. Are text data that can be manipulated using a character stream while increasing efficiency and adding buffering. */import java.io.*;import java.net.*;class  transclient{public static void  Main (String[] args)  throws exception{socket s = new socket ("127.0.0.1", 10005);//defines the stream object that reads the keyboard data. Bufferedreader bufr = new bufferedreader (New inputstreamreader (System.in));//definition purposes, Writes data to the socket output stream. Sent to the service side. Bufferedwriter bufout = //new bufferedwriter (New outputstreamwriter ( S.getoutputstream ())); Printwriter out = new printwriter (S.getoutputstream (), true);//defines a socket read stream that reads the uppercase information returned by the server. Bufferedreader bufin = new bufferedreader (New inputstreamreader (S.getInputStream ())); String line = null;while ((line=Bufr.readline ())!=null) {if (' over '. Equals (line)] Break;out.println (line),//bufout.write (line);//bufout.newline () ;//bufout.flush (); String str =bufin.readline (); SYSTEM.OUT.PRINTLN ("server:" +str);} Bufr.close (); S.close ();}} /* Server: Source: Socket read stream. Purpose: the socket output stream. It's all text and decorations. */class  transserver{public static void main (String[] args)  throws  Exception{serversocket ss = new serversocket (10005); Socket s = ss.accept (); String ip = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected");//Read the socket read the data in the stream. Bufferedreader bufin =new bufferedreader (New inputstreamreader (S.getInputStream ()));//purpose. Socket output stream. Writes uppercase data to the socket output stream and sends it to the client. Bufferedwriter bufout = //new bufferedwriter (New outputstreamwriter ( S.getoutputstream ())); Printwriter out = new printwriter (S.getoutputstream (), true); String line = null;while ((Line=bufin.reaDline ())!=null) {System.out.println (line); Out.println (Line.touppercase ());//bufout.write (Line.touppercase ());// Bufout.newline ();//bufout.flush ();} S.close (); Ss.close ();}} /* The problem occurs with this example. Phenomenon: The client and the service side are in inexplicable wait. Why is it? Because both the client and the server have a blocking method. These methods do not read to the closing tag. So it has been waiting to lead to both ends, are waiting. */



3. Uploading text files

import java.io.*;import java.net.*;//Uploading Files Class  textclient{public static void  main (String[] args)  throws exception{socket s = new socket ("127.0.0.1 ", 10006); Bufferedreader bufr = new bufferedreader (New filereader ("IPDemo.java")); Printwriter out = new printwriter (S.getoutputstream (), true); String line = null;while ((Line=bufr.readline ())!=null) {out.println (line);} S.shutdownoutput ();//Closes the client's output stream. Equivalent to adding an end tag to the stream-1. Bufferedreader bufin = new bufferedreader (New inputstreamreader (S.getInputStream ())); String str = bufin.readline (); System.out.println (str); Bufr.close (); S.close ();}} Class  textserver{public static void main (String[] args)  throws  Exception{serversocket ss = new serversocket (10006); Socket s = ss.accept (); String ip = s.getinetaddresS (). Gethostaddress (); System.out.println (ip+ ".... Connected"); Bufferedreader bufin = new bufferedreader (New inputstreamreader (S.getInputStream ())); Printwriter out  = new printwriter (New filewriter ("Server.txt"), true); String line = null;while ((Line=bufin.readline ())!=null) {//if ("over". Equals (line))//break;o Ut.println (line);} Printwriter pw = new printwriter (S.getoutputstream (), True);p w.println ("Upload succeeded"); Out.close (); S.close (); Ss.close ();}}


4. Upload images support concurrency

/* Requirements: Upload images. *//* client. 1, service endpoint. 2, read the client's existing picture data. 3, the data is sent to the server via the socket  output stream. 4, read the service side feedback information. 5, close. */import java.io.*;import java.net.*;class  picclient{public static void  Main (String[] args) throws exception {if (args.length!=1) {System.out.println ("Please select a jpg format picture"); return ;} File file = new file (Args[0]); if (!) ( File.exists ()  && file.isfile ()) {System.out.println ("The file has a problem, either does not exist, or is not a file"); return ;} if (!file.getname (). EndsWith (". jpg")) {System.out.println ("Picture format is wrong, please re-select"); return ;} if (File.length () >1024*1024*5) {System.out.println ("The file is too large, not Ann-hearted"); return ;} Socket s = new socket ("127.0.0.1", 10007); 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);} Tell the server that the data has been finished S.shutdownoutput ();inputstream In = s.getinputstream ();byte[] bufin = new byte[1024];int num =  In.read (Bufin); System.out.println (new string (Bufin,0,num)); Fis.close (); S.close ();}} /* Server This server has a limitation. When a client is connected on the later. Be acquired by the server. The service side executes the specific process. At this point the B client connects and waits only. Because the server has not finished processing the a client's request, there is a loop back to execute the next accept method. Therefore, the B client object is not available temporarily. So that multiple clients can concurrently access the server at the same time. It is best to encapsulate each client in a separate thread so that multiple client requests can be processed at the same time. How do I define a thread? Just define the code that each client will execute on the server. Save the code in the Run method. */class picthread implements runnable{private socket s; Picthread (socket s) {this.s = s;} Public void run () {int count = 1; String ip  = s.getinetaddress (). gethostaddress (); Try{system.out.println (ip+ ".... Connected" ); Inputstream in = s.getinputstream (); File dir =  new file ("D:\\pic"); File file = new file (dir,ip+ "(" + (count) + ")" + ". jpg"), while (File.exists ()) file =  New file (dir,ip+ "(" + (count++) + ")" + ". jpg"); Fileoutputstream&nbSp;fos = new fileoutputstream (file);byte[] buf = new byte[1024];int  Len = 0;while ((Len=in.read (BUF))!=-1) {fos.write (Buf,0,len);} Outputstream out = s.getoutputstream (); Out.write ("Upload succeeded". GetBytes ()); Fos.close (); S.close ();} catch  (exception e) {throw new runtimeexception (ip+ "upload failed");}}} Class  picserver{public static void main (String[] args)  throws  Exception{serversocket ss = new serversocket (10007); while (true) {socket s =  Ss.accept (); New thread (New picthread (s)). Start (); Ss.close ();}}

5. Login

/* Client input user name via keyboard. This user name is verified by the server. If the user exists, on the server display XXX, has landed. And in the client display  xxx, welcome to visit. If the user exists, show xxx on the server and try to log in. And  xxx is displayed on the client, the user does not exist. Log in at most three times. */import java.io.*;import java.net.*;class  loginclient{public static void  Main (String[] args)  throws exception{socket s = new socket ("127.0.0.1", 10008); Bufferedreader bufr = new bufferedreader (New inputstreamreader (System.in)); Printwriter out = new printwriter (S.getoutputstream (), true); Bufferedreader bufin =new bufferedreader (New inputstreamreader (S.getInputStream ())); int x=0; x<3; x++) {string line = bufr.readline (); if (line==null) Break;o Ut.println (line); String info = bufin.readline (); System.out.println ("info:" +info); if (Info.contains ("Welcome") break;} Bufr.close (); S.close ();}} class userthread implements runnable{private socket s; Userthread (socket s) {thIs.s = s;} Public void run () {string ip = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connected"); Try{for (int x=0; x<3; x++) {Bufferedreader bufin  = new bufferedreader (New inputstreamreader (S.getinputstream ())); String name = bufin.readline (); if (name==null) break; Bufferedreader bufr = new bufferedreader (New filereader ("User.txt")); Printwriter out = new printwriter (S.getoutputstream (), true); String line = null;boolean flag = false;while ((Line=bufr.readLine ())!=null) {if ( Line.equals (name)) {flag = true;break;}} if (flag) {System.out.println (name+ ", Logged in"), Out.println (name+ ", welcome"); Else{system.out.println (name+ ", try to log in"), Out.println (name+ ", user name does not exist");}} S.close ();} catch  (exception e) {throw new runtimeexception (ip+ "checksum failed");}}} class  loginserver{public static void Main (String[] args)  throws exception{serversocket ss = new serversocket ( 10008); while (true) {socket s = ss.accept (); New thread (New userthread (s)). Start ();}}


This article is from the "bit accumulation" blog, please be sure to keep this source http://tianxingzhe.blog.51cto.com/3390077/1742473

Big summary of Socket programming

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.