A previous blog post devoted to the basic concept of sockets, where Java is used to implement a simple server-client socket data transfer.
Server Side
/** * SOCKET Service side * * @author Peter_wang * @create-time 2014-8-30 pm 3:25:27 */public class Server {public static void M Ain (String args[]) throws IOException {int port = 8888; ServerSocket Server = new ServerSocket (port); while (true) {//begins to accept the socket request Socket socket = server.accept (); A new thread is created to process the new socket request, and it is a fresh Task (socket). Start (); }}/** * Asynchronous task handling Socket Request */Static class task implements Runnable {private Socket Msocket ; Public Task (socket socket) {this.msocket = socket; } public void Run () {try {handlesocket (); } catch (Exception e) {e.printstacktrace (); }}/** * communicates with the client socket * * @throws Exception */private void Handl Esocket () throws Exception {BufferedReader br = new BuffEredreader (New InputStreamReader (Msocket.getinputstream (), "UTF-8")); StringBuilder sb = new StringBuilder (); String temp; int index; while ((temp = br.readline ()) = null) {//encounters EOF when end receives if (index = Temp.indexof ("EOF"))! = -1) {System.out.println (temp); Sb.append (temp.substring (0, index)); Break } sb.append (temp); } System.out.println ("Data from client:" + SB); Write operation writer writer = new OutputStreamWriter (Msocket.getoutputstream ()); Writer.write ("Hello Client."); Writer.write ("eof\n"); Writer.flush (); Writer.close (); Br.close (); Msocket.close (); } }}
Client Side
/** * Socket Client * * @author Peter_wang * @create-time 2014-8-30 pm 4:13:11 */public class Client {public static void M Ain (String args[]) throws Exception {string host = "127.0.0.1";//local address int port = 8888; Connect to the server socket client = new socket (host, port); Scanner sc = new Scanner (system.in); String str = sc.nextline (); SYSTEM.OUT.PRINTLN ("Input content:" + str); After the connection is established, the data can be written to the server. Writer writer = new OutputStreamWriter (Client.getoutputstream (), "UTF-8"); Writer.write (str); Writer.write ("eof\n"); Writer.flush (); After writing, read operations BufferedReader br = new BufferedReader (New InputStreamReader (Client.getinputstream ())); StringBuffer sb = new StringBuffer (); String temp; int index; while ((temp = br.readline ()) = null) {if (index = Temp.indexof ("EOF"))! =-1) {Sb.append (te Mp.substring (0, index)); Break } Sb.append (temp); } System.out.println ("From server:" + SB); Writer.close (); Br.close (); Client.close (); }}
1. Use EOF to finish the read and write end identity.
2.BufferedReader improves IO efficiency, prepares data to memory asynchronously, reads directly from memory, and if the data originates from disk IO or network IO, the speed is much faster, and the speed of disk reads and memory reads is compared in this article.
Data transfer between 3.server and client requires a uniform encoding to prevent garbled characters.
4. Source analysis, the server-side new ServerSocket (port) implements the new socket, bind, listener function
public void bind (socketaddress endpoint, int backlog) throws IOException {if (isClosed ()) throw new SocketException (' So Cket is closed "), if (!oldimpl && isbound ()) throw new SocketException (" Already bound "); if (endpoint = = null) Endpoint = new Inetsocketaddress (0); Endpoint instanceof Inetsocketaddress)) throw new IllegalArgumentException ("Unsupported address type"); Netsocketaddress epoint = (inetsocketaddress) endpoint;if (epoint.isunresolved ()) throw new SocketException ("Unresolve D address "), if (backlog < 1) Backlog = 50;try {SecurityManager security = System.getsecuritymanager (); if (Security! = null) Security.checklisten (Epoint.getport ()); Getimpl (). Bind (Epoint.getaddress (), Epoint.getport ()); Getimpl (). Listen (backlog); bound = true;} catch (SecurityException e) {bound = false; throw e;} catch (IOException e) {bound = false; throw e;} }The new socket (host, port) on the client side provides the ability to connect
Private Socket (socketaddress address, socketaddress localaddr, Boolean stream) throws IOException {Setimpl ();// Backward Compatibilityif (address = = null) throw new NullPointerException (); try { Createimpl (stream) ; if (localaddr! = null) bind (LOCALADDR); if (address = null) connect (address);} catch (IOException e) { close (); throw e;} }
Java-socket programming