Brief introduction
The sockets were originally called Berkeley sockets, since the university was originally invented by Berkeley. In Java, it is convenient to call the socket for network communication. Below, try to read and write data to the remote server using sockets.
Code Demo
Package Demo0811.demo1;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.IOException; Import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.outputstreamwriter;import java.io.writer;import java.net.socket;/** * Apply socket for word meaning query * @author ZZW * */public Class Dictionaryclient {private Socket socket=null;private static final int timeout=20000;private static final String SERV Er= "dict.org";p rivate static final int port=2628;public dictionaryclient (string[] words) throws Exception {Socket=new Socket (Server,port); Socket.setsotimeout (TIMEOUT); OutputStream outputstream = Socket.getoutputstream (); Writer outputstreamwriter = new OutputStreamWriter (outputstream); Outputstreamwriter=new BufferedWriter ( OutputStreamWriter); InputStream InputStream = Socket.getinputstream (); BufferedReader BufferedReader = new BufferedReader (new InputStreamReader (InputStream, "UTF-8")); for (String word:words ) define (Word,outputstreamwriter,bufferedreader);} private static void define (String word,writer Writer,bufferedreader reader) {try {writer.write ("define Eng-lat" +word+ "\ r\n "), Writer.flush (), for (String line=reader.readline (); Line!=null;line=reader.readline ()) {if (Line.startswith (" ) {return,} else if (Line.startswith ("552")) {System.out.println ("No definition for" +word); return;} else if (line.matches ("\\d\\d\\d. *")) {continue;} else if (Line.trim (). Equals (".")) {continue;} else {System.out.println (line);}}} catch (IOException e) {e.printstacktrace ();}}}
Test code
Package Demo0811.demo1;public class Test {public static void main (string[] args) throws Exception {string[] words={"You", " Computer "," Sky "};new dictionaryclient (words);}}
Java sockets program reads and writes data to the server