Java Basics Nine [Networking and threading] (reading head first Java Records)

Source: Internet
Author: User

Network socket Connectionthe Java API's Network Feature Pack (java.net) has encapsulated the underlying TCP connection, and we only need to connect the client and server through the socket object, and then the client can send a request to the server and receive the data from the service side the approximate interaction between the server and the client is as follows:  Writing client Programs Step One: Establish a socket connectionthe following connections need to be established on both the client and server sideSocket chatsocket=new Socket ("Counterparty IP Address", TCP port number); IP-like number, do addressing, find the server. The port number is to find a program on this server a port number is a number used to identify a specific program on a server that uniquely identifies a program on a single machine .the port number on each server is limited to 0~65536, and 0~1023 is reserved for known specific services (for example, HTTP has a port of 80,https of 443), so our own program uses the 1024~65536 port number. And do not conflict with the current machine's existing program port number  Step Two: Write data to the socket with PrintWriter1. Create a printwriter link to the socketprintwriter writer=new PrintWriter (Chatsocket.getoutputstream ()); 2. Writing Datawriter.println ("message to send");Writer.print ("another Message");  Step Three: Use BufferedReader to read data from the socketThe socket can be connected with a stream of communication, and the previous chapter of the file to the object of the stream, we do not care what the upstream is actually, as long as the stream BufferedReader can receive 1. InputStreamReader for low-level input streams from socket connectionsInputStreamReader stream = new InputStreamReader (Chatsocket.getinputstream ()); 2. Build BufferedReader to read InputStreamReaderBufferedReader reader= new BufferedReader (stream);String message=reader.readline ();  write a simple server program the server's reference program needs to create two sockets. A serversocket used to wait for a user request, and a socket to communicate with the user.   First step: Create ServerSocket with a specific portserversocket serversock=new ServerSocket (4242);//The server will listen to 4242 Port client requests  Step Two: The client establishes a socket connection to the server reference programSocket sock=new Socket ("127.0.0.1", 4242);//server IP and listening port  Step Three: The server creates a new socket to communicate with the clientSocket sock=serversock.accept ();accept () wait for the user to connect, if there is a user connection will return a and serversocket different port number of the socket, through the above-mentioned printwriter to send data to the clientIf there is no user connection, then the program will remain in the accept () This step, until a user is connected to perform the next step Note: It is important to start the server before the client can connect with the server, or it will throw an exception that is not connected to the socket When do we go to the interface server to return the request? To query the server once in a while? Or do you check each time you send a message? is not very reasonable (because we have to have a socket to query). Java has multiple threads, enabling a single thread to be opened and waiting for server information  Java multithreaded Multithreading Thread: The thread is independent and has a separate execution space. Each Java program starts a main thread (main ()), and the program needs to create the other threads it needs.The thread is not actually executing concurrently (unless it is multiprocessor), it switches different threads within 100 milliseconds to execute (as determined by the thread scheduling mechanism of the Java Virtual Machine), making people feel that they are processing in parallel Use the Java.lang.Thread class to create a thread that has a way to start a thread, connect threads, and leave threads idle  here's how to start a thread:Runnable threadjob=new myrunnable ();//The task to be performed by the thread, Runnable is an interface with only one public void run () {} methodthread t=new thread (threadjob);//Create a thread object and assign a value runnable taskT.start ();//Start thread, only then open a thread and perform runnable task  Thread Description:1. You can also create a new process by inheriting the thread, which subclasses rewrite the run () method, but this method does not recommend2.run () is the first method performed by a new thread3. After the thread has finished executing run (), it cannot be restarted again.4. The thread start () is in the executable state5. When the scheduler selects a thread, it is in an executable state, and a single-processor machine can have only one thread in execution6. Scheduling is not necessarily completely fair, not all machine scheduling is exactly the same7. Sometimes threads are blocked for some reason8. Adding sleep () forces the executing thread to leave the in-execution state to hibernate when the sleep time has ended and becomes executable state  problems caused by thread concurrency: data access or update issuesIf multiple threads manipulate one of the data (getter or setter) of the same object, it can cause serious problems if other threads are referencing without querying the state of the current data. (for example, the example of a query after the balance is sufficient to enter the executable state, b spent money; A again into the state of execution without checking the balance of direct spending, resulting in insufficient balance of the case of the deduction of money) Workaround: Add a synchronization method with the synchronized keywordFor example private synchronized void Makewithdrawal (int amount) {}Description: Each object is a lock with only one key per lock. Usually the object is not locked, only to see the synchronized synchronized method will be locked, the goal of synchronization is to protect important data, the actual lock is the method of accessing data. The key will be released only when the Synchronized method is finished. problems caused by synchronization: deadlock, if the synchronized two processes need each other to hold what the other is waiting for, it will cause a deadlock   

Java Basics Nine [Networking and threading] (reading head first Java Records)

Related Article

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.