Java-socket programming, logging ocket

Source: Internet
Author: User

Java-socket programming, logging ocket

Previously, I wrote a blog post specifically on the basic concept of socket. Here I use java to implement simple socket data transmission for server-client.

Server

/*** Socket Server ** @ author peter_wang * @ create-time 3:25:27 */public class Server {public static void main (String args []) throws IOException {int port = 8888; ServerSocket server = new ServerSocket (port); while (true) {// start to accept socket request Socket socket = server. accept (); // create a new Thread to process the new socket request new Thread (new Task (socket )). start () ;}}/*** asynchronous Task for processing Socket requests */static class Task implement S 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 handleSocket () throws Exception {BufferedReader br = new BufferedReader (new InputStreamReader (mSocket. getInputStream (), "UTF-8"); StringBuilder sb = new Stri NgBuilder (); String temp; int index; while (temp = br. readLine ())! = Null) {// end receiving if (index = temp. indexOf ("eof") When eof is encountered "))! =-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

/*** Socket Client ** @ author peter_wang * @ create-time 4:13:11 */public class Client {public static void main (String args []) throws Exception {String host = "127.0.0.1"; // local address int port = 8888; // establish a connection with the server Socket client = new Socket (host, port ); using SC = new using (System. in); String str = SC. nextLine (); System. out. println ("input content:" + str); // after a connection is established, you can write data to the server. Writer writer = new OutputStreamWriter (client. getOutputStream (), "UTF-8"); writer. write (str); writer. write ("eof \ n"); writer. flush (); // read BufferedReader after writing; 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 (temp. substring (0, index); break;} sb. append (temp);} System. out. println ("from server:" + sb); writer. close (); br. close (); client. close ();}}

1. Use the eof to complete the read/write end identifier.

2. bufferedReader improves I/O efficiency. Data is prepared asynchronously in advance to be stored in the memory and read directly from the memory. If the data comes from disk I/O or network I/O, the speed will be much faster, for the speed comparison between disk reading and memory reading, see this article.

3. Unified encoding is required for data transmission between the server and client to prevent garbled characters.

4. source code analysis: the new ServerSocket (port) on the server implements the new socket, bind, and listener functions.

public void bind(SocketAddress endpoint, int backlog) throws IOException {if (isClosed())    throw new SocketException("Socket is closed");if (!oldImpl && isBound())    throw new SocketException("Already bound");if (endpoint == null)    endpoint = new InetSocketAddress(0);if (!(endpoint instanceof InetSocketAddress))    throw new IllegalArgumentException("Unsupported address type");InetSocketAddress epoint = (InetSocketAddress) endpoint;if (epoint.isUnresolved())    throw new SocketException("Unresolved 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 implements the new socket and connect functions.

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

This is because the port is always occupied without being closed after the program is run for you, so it will throw an exception

Where can java socket programming be used?

For Process Communication, Baidu encyclopedia is recommended.

Simple Client/Server program
1. Client Program
Import java. io. *; import java.net. *; public class TalkClient {public static void main (String args []) {try {Socket socket = new Socket ("127.0.0.1", 4700 ); // send the customer request BufferedReader sin = new BufferedReader (new InputStreamReader (System. in); // The BufferedReader object PrintWriter OS = new PrintWriter (socket. getOutputStream (); // get the output stream from the Socket object and construct the PrintWriter object BufferedReader is = new Buff EredReader (new InputStreamReader (socket. getInputStream (); // obtain the input stream from the Socket object and construct the corresponding BufferedReader object String readline; readline = sin. readLine (); // read a string from the system standard input while (! Readline. equals ("bye") {// If the string read from the standard input is "bye", the cyclic OS is stopped. println (readline); // outputs the string read from the system standard input to the Server OS. flush (); // refresh the output stream so that the Server immediately receives the string System. out. println ("Client:" + readline); // print the read string System on the System standard output. out. println ("Server:" + is. readLine (); // read a string from the Server and print it to the standard output. readline = sin. readLine (); // read a string from the system standard input} // continue loop OS. close (); // close the Socket output stream is. close (); // close Socket input stream socket. close ();/& amp; #4 ...... remaining full text>

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.