Javase socket programming __java that path

Source: Internet
Author: User
Tags readline thread class throw exception wrapper
TCP Communications





Server:package day07;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.net.ServerSocket;

Import Java.net.Socket;
    /** * Server-side application * @author Administrator */public Class Server {//the socket private ServerSocket server running on the server;
            /** * Constructs a method for initializing the service-side * @throws IOException/Public Server () throws ioexception{try {
            * * * When creating serversocket you need to specify a service port/System.out.println ("Initialization Server");
            Server = new ServerSocket (8088);
        SYSTEM.OUT.PRINTLN ("server-side initialization complete");
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); No success was created.
        Throw exception throw E; }/** * Service-side Start working method/public void Start () {try{/* ServerSocket
            The Accept method * is used to listen on port 8088 and wait for the client to link * This method is a blocking method until a client link, otherwise the method is blocked.
            * If a client link, it will return the client's socket */SYSTEM.OUT.PRINTLN ("Waiting for the client to connect ...");
            Socket socket=server.accept ();


            SYSTEM.OUT.PRINTLN ("Client Connected");
            Receive message from client//inputstream input stream InputStream is = Socket.getinputstream ();
           into character streams ...
           InputStreamReader ISR = new InputStreamReader (IS);
           Converts a character stream to a buffered stream input flow so that the string can be read by behavior unit bufferedreader br = new BufferedReader (ISR);

           String message; while ((Message=br.readline ())!=null) {System.out.println ("client:" + "IP:" +socket.getinetaddress () + ":" +socket.getpor
           T () + "::" +message);
            //If ReadLine returns NULL, it means that the information cannot be read again//windows: the ReadLine () method throws an exception after the client disconnects from the server}catch (Exception e) {
        E.printstacktrace ();
        } public static void Main (string[] args) {Server server = NULL; try {server = new Server ();
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); SYSTEM.OUT.PRINTLN ("Server-side initialization failed.")
        ");
    } server.start (); }

}
Client:package day07;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;

Import Java.util.Scanner;
    public class Client {//socket, which is used to connect the ServerSocket private socket socket on the service side; The constructor method initializes the client public client () {try {* * * * * To create the socket object, attempting to connect the server to the port based on the given address.
            So, * If the object is created successfully, it is connected with the service side normal * * * socket = new Socket ("127.0.0.1", 8088);
        SYSTEM.OUT.PRINTLN ("Successful Connection Service End");
        The catch (Unknownhostexception e) {//Port number exception e.printstacktrace ();
            catch (IOException e) {System.out.println ("Client creation failed");
        E.printstacktrace ();
             }//Client startup method public void Start () {try{/* * Can be passed through the socket Getoutputstream ()
      * method to obtain an output stream, the user and information sent to the service side * is a byte stream, * *  OutputStream out = Socket.getoutputstream ();
        It's easier to write a stream of characters.
        OutputStreamWriter OSW = new OutputStreamWriter (out);
        Buffer flow on the wrapper writes the string in the behavior unit printwriter PW = new PrintWriter (OSW); 
        while (true) {Scanner Scanner = new Scanner (system.in);
        Pw.println (Scanner.next ()); If you do not write, it will not appear because it is a buffered stream. And there is no output.
        Flush yourself.
        Pw.flush ();
        }}catch (Exception e) {e.printstacktrace ();
        } public static void Main (string[] args) {Client client = new Client ();



    Client.start (); }

}
Summary:

Creating a class and then defining a socket, as server and client, starts with simply defining the socket type and not initializing it. Implements the constructor, the server's constructor writes the port, the server = new ServerSocket (), and the IP is the one on which it is running. Client is the IP and port socket of the incoming server = new socket (IP, port)

You will then create a start function to use as a function after the Sockt connection.
Server to wait for connection; The Accept call Accpet is in start.

Socket socket=server.accept ();

The socket created is the socket that connects the client

Then create a server in the main function
Server = new server (); Call start function
Then write how to transfer the characters in start. Socket has a Getoutputstream method, but the return is a byte stream, then it is necessary to turn the character stream is OutputStreamWriter, and then add a buffer flow, a line of read and write operations PrintWriter
Server:getinputstream InputStreamReader BufferedReader

Clent:getoutputstream OutputStreamWriter
PrintWriter

Read operation, if the ReadLine return is NULL then there is no information to read.
Be aware of flush () multithreaded service side

Package day07;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.net.ServerSocket;

Import Java.net.Socket;

        /** * Java multi-threaded socket * @author Administrator */public class ThreadServer2 {private ServerSocket server;
            Public ThreadServer2 () {try {server = new ServerSocket (8088);
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } public void Start () {while (true) {System.out.println ("Server waits for connection ...")
            );
                try {Socket socket = server.accept (); 
                Call thread, incoming socket hthread ht1 = new Hthread (socket);

            Ht1.start ();
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();



    }//catch        }//while}//start public static void Main (string[] args) {//Create boot server new Threadser directly

    Ver2 (). Start ();
        }//Thread class, call the thread in start, and pass in the socket class Hthread extends thread {private socket socket;
            Public hthread (socket socket) {this.socket = socket; SYSTEM.OUT.PRINTLN ("Client connection succeeded.)

        "); public void Run () {try {//Receive data inputstream is = Socket.getinputstr

                EAM ();

                InputStreamReader ISR = new InputStreamReader (IS);
                BufferedReader br = new BufferedReader (ISR);
                String message; while (message = Br.readline ())!=null) {System.out.println ("Client: IP:" +socket.getinetaddress () + "PORT"
                +socket.getport () + ":" +message); }//while} catch (IOException e) {//TODO auto-generated catch block e.prints
            Tacktrace (); }finaLly{try {socket.close ();
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}


        }


    }

}
use runnable, and then use the thread pool:
Package day07;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; Import day07.

Threadserver2.hthread;
    public class Threadciserver {private ServerSocket server;

    Private Executorservice ThreadPool;
            Public threadciserver () {try {server = new ServerSocket (8088);


        Create a thread pool that runs up to 50 ThreadPool =executors.newfixedthreadpool (2);
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
        } public void Start () {while (true) {System.out.println ("Server waits for Connection ...");
            try {Socket socket = server.accept (); 

            Call thread, incoming socket Runnable ht1 = new Hthread (socket);

        Threadpool.execute (HT1); Catch (IOException e)
        {//TODO auto-generated catch block E.printstacktrace (); }//catch}//while}//start public static void Main (string[] args) {//Create boot server new ThreadServer2 directly

(). Start ();
    }//Thread class, call the thread in start, and pass in the socket class Hthread implements Runnable {private socket socket;
        Public hthread (socket socket) {this.socket = socket; SYSTEM.OUT.PRINTLN ("Client connection succeeded.)

    ");

            public void Run () {try {//Receive data InputStream is = Socket.getinputstream ();

            InputStreamReader ISR = new InputStreamReader (IS);
            BufferedReader br = new BufferedReader (ISR);
            String message; while (message = Br.readline ())!=null) {System.out.println ("Client: IP:" +socket.getinetaddress () + "PORT" +soc
            Ket.getport () + ":" +message); }//while} catch (IOException e) {//TODO auto-generated catch block e.printstacktrAce ();
        }finally{try {socket.close ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

    } System.out.println ("A client is offline ..."); }


}

}
also summary:

Returns, the server directly defines the output stream, and then in run the original is the output of the information in the display, directly on the PW.PRINTLN (); Send the past.
Then it's more complicated in the client. Not only the client, and then the server, in return to the client, regardless of whether the client is sent, there is information sent to the client, then define an input stream. But to create a separate thread for him, the collection and the hair is not synchronized. A thread is the same as receiving a server. Call the Create thread in the Start method.

Server:package day07;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.concurrent.ExecutorService;

Import java.util.concurrent.Executors; Import day07.

Threadciserver.hthread;
    public class Server_fanui {private ServerSocket Server;

    Private Executorservice ThreadPool;
            Public Server_fanui () {try {Server = new ServerSocket (8088);


        Create a thread pool that runs up to 50 ThreadPool =executors.newfixedthreadpool (50);
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
        } public void Start () {while (true) {System.out.println ("Server waits for Connection ...");
            try {Socket socket = server.accept ();
   Calling thread, passing in the socket         Runnable ht1 = new Hthread (socket);

        Threadpool.execute (HT1);
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }//catch}//while}//start public static void Main (string[] args) {//Create boot server new ThreadServer2 directly

(). Start ();
    }//Thread class, call the thread in start, and pass in the socket class Hthread implements Runnable {private socket socket;
        Public hthread (socket socket) {this.socket = socket; SYSTEM.OUT.PRINTLN ("Client connection succeeded.)

    ");

            public void Run () {try {outputstream OS = Socket.getoutputstream ();

            OutputStreamWriter OSR = new OutputStreamWriter (OS);

            PrintWriter pw = new PrintWriter (osr,true);

            Receive data InputStream is = Socket.getinputstream ();

            InputStreamReader ISR = new InputStreamReader (IS);
            BufferedReader br = new BufferedReader (ISR);
          String message;  while (message = Br.readline ())!=null) {//System.out.println ("Client: IP:" +socket.getinetaddress () + "PORT" +s
                Ocket.getport () + ":" +message);


            PW.PRINTLN (message); 
        }//while} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
        }finally{try {socket.close ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

    } System.out.println ("A client is offline ..."); }


}

}
Client:package day07;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;

Import Java.util.Scanner; Import day07.

Client.getserver;
        public class Client_fanhui {//socket, which is used to connect the ServerSocket private socket socket of the server; constructor to initialize the Client public Client_fanhui () {try {* * * * * * To create a socket object, you will try to Connect the server to the port based on the given address.
                So, * If the object is created successfully, it is connected with the service side normal * * * socket = new Socket ("127.0.0.1", 8088);
            SYSTEM.OUT.PRINTLN ("Successful Connection Service End");
            The catch (Unknownhostexception e) {//Port number exception e.printstacktrace ();
                catch (IOException e) {System.out.println ("Client creation failed");
     E.printstacktrace ();       }///client Startup method public void Start () {try{Runnable rserver = new
                Getserver ();
                Thread tserver = new Thread (rserver);

                Tserver.start ();
                 * * You can get an output stream via the Getoutputstream () * Method of the socket, where the user and the message are sent to the service side * is a byte stream,
                * * OutputStream out = Socket.getoutputstream ();
            It's easier to write a stream of characters.
            OutputStreamWriter OSW = new OutputStreamWriter (out);
            Buffer flow on the wrapper writes the string in the behavior unit printwriter PW = new PrintWriter (osw,true); 
            while (true) {Scanner Scanner = new Scanner (system.in);

            Pw.println (Scanner.next ()); If you do not write, it will not appear because it is a buffered stream. And there is no output.
            Flush yourself.
            }}catch (Exception e) {e.printstacktrace ();
   } public static void Main (string[] args) {Client client = new Client ();         Client.start ();
        //Create a thread, one is the original data to the server, this is to receive data to the server.
                    Class Getserver implements runnable{@Override public void Run () {try{

                System.out.println ("6666");

                InputStream is = Socket.getinputstream ();

                InputStreamReader ISR = new InputStreamReader (IS);
                BufferedReader br = new BufferedReader (ISR);
                String Message=null;
                while ((Message=br.readline ())!=null) {System.out.println ("server:" +message);
                }}catch (Exception e) {e.printstacktrace (); }}//run}//class_getserver}
If you are creating a multiplayer online chat method

Save all client output streams by creating a public list of other clients that are different threads on the server. The list is a stream. So the List is defined, initialized in the constructor.

The output of the client is present in a shared collection so that the client can also accept messages forwarded by the server

Append (PW)
The stream is stored in the collection ... Not the string inside the stream ... A client corresponds to a stream in a list ....
If the client is disconnected, the corresponding stream in the list will also be deleted. Remove (PW)

Count Current online numbers ... The size of the list is

Send a message to a client, all the streams in the variable list are sent over. Implementing Group Chat

However, there will be multiple threads simultaneously operating the shared collection list ... Thread safety issues

Iterate over this set, which is iterator, not thread safe, and traversal is not synchronized with Add and remove.
To ensure that the traversal is also synchronized, three are synchronized.

If it's mutually exclusive. Then the sync lock is also called a mutual exclusion lock.

When we call a static method, we do not need to be an instance of the husband, which can be invoked directly by the class name.

Static methods and static properties are shared for all instances

Because multiple threads manipulating a list can cause thread-unsafe problems (add and remove, traversal is OK)
With synchronized
If two threads see a synchronized is a synchronous lock, cannot access simultaneously

But this is mutual exclusion, different places lock the same object, is the mutual exclusion lock

You can put the output stream into the map and define a name for each output stream.
Then you can click on the @ nickname, then go to the map to find the individual output, otherwise it is all output UDP communication

Unreliable transport protocol
The stream used on the TCP connection. Continuous output writes to each other
But UDP is not a long connection.

No need to wait for each other, consume less
The main learning is packaging and unpacking, packaging sent to the past, received after the unpacking
Datagrampacket
Building a Receive Package

Constructing a Send Package

Service-side Receive
Datagramsocket

When instantiated, give a port number, or the ports on the server to be fixed

Receive receiving data

Client sends
Both ends are datagramsocket.

server:package day07;
Import Java.net.DatagramPacket;

Import Java.net.DatagramSocket;
            /** * UDP Server * @author Administrator * * */public class Udpserver {public void start () {try{  * * Steps to receive packages * Create socket * Create a suitable size package * receive data via SOCKET to package * Unpacking fetch data//server when creating socket to pass parameter port datagramsocket Server = new DATAGRAMSOC Ket (8088); 

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.