Multithreaded programming and Java Network programming

Source: Internet
Author: User

1. Threading Overview

There are two types of multitasking: process-based, thread-based (process refers to a "self-containment" running program, with its own address space; A thread is a single sequential control flow within a process)

Process-based features allow a computer to run two or more programs at the same time, a thread-based multitasking environment in which the thread is the smallest processing unit

2. Creating and Starting Threads

A. Methods for creating Threads:

A. Write a class that inherits the thread class, and then override the run () method of the Thread class

public class Thread extends thread {

public void Run () {

}

public static void Main (string[] args) {

Thread d = new Thread ();

D.start ();

}

}

B. Write a class to implement the Runnable interface, and then associate an instance of the class with the thread object

public class ThreadRun implements Runnable {public void run () {

}

public static void Main (string[] args) {

ThreadRun td = New ThreadRun ();

Thread t = new Thread (TD);

T.start ();

}

}

3. Priority of Threads

A. Thread precedence in Java is a constant defined in the thread class:

Norm_priority: A value of 5

Max_priority: A value of 10

Min_priority: A value of 1

B. There are two ways to prioritize:

A. final void setpriority (int newp): Modify the thread's current priority

B. Final int getpriority (): Returns the priority of the thread

4. Conditions that enable threads to suspend execution

A. Using the sleep () method to make the thread sleep

B. Make the thread wait by calling the Wait () method

C. The thread has explicitly assigned CPU control by calling the yield () method

D. Thread is blocked waiting for an I/O event

5. Thread synchronization: Using the Sync keyword synchronized

A Ways to resolve thread synchronization:

A. Synchronization block

Syntax: Synchronized (the object that acquired the lock) {

The code to lock

}

B. Synchronization method: Use synchronized in front of method name keyword adornments

6. Deadlock: Deadlock occurs when two threads cycle dependent on a pair of synchronization objects

7. Mutual communication between threads

Method:

A.wait (): tells the called thread to exit the monitor and enter the wait state until another thread enters the same monitor and calls the Notify () method B.notify (): Notifies the first call to the same object on the wait () thread C.notifyall (): Notification calls wait () of all threads, the thread with the highest priority will run first 8.OSI Model: ISO provides an OSI reference model that divides the network into seven tiers 9.TCP/IP ProtocolA. Addressing and locating programs on a network host

A. The essence of network programming is to write programs that communicate directly or indirectly to a program on other computers through a network protocol.

B. How can I find a program to communicate on a host on the network?

C. Provide the IP address and port number, you can find the specified host on the network to communicate on the specified program

B. PORT: Used to implement inter-program communication c. How can I transfer data to a host program on a network?

A. Data transfer is the responsibility of the transport layer in the TCP/IP tiered model, which contains TCP and UDP two protocols

B. TCP protocol: More reliable bidirectional streaming protocol, sending any number of data, providing message acknowledgement, error detection and error recovery services

C. UDP protocol: Compare unreliable

10. Client and server

A. The server and client share the burden of computing

A. Customer: Computer requesting service from another computer

B. Server: The computer that handles client requests

11. Socket (socket): is the endpoint of Internet communication and the client and server connect and communicate through sockets 12.Java support for network programming

JDK pre-defined network programming related classes are stored in the java.net package.

Common classes: inetaddress, sockets, ServerSocket and SocketImpl, Datagrampacket and Datagramsocket, URLs, URLConnection, and Urlencoder

A.inetaddress class: Is the IP address and DNS used to encapsulate the computer

The class does not have a constructor method, so you cannot create an object directly from the New keyword. We can use the following common methods to get the class object:

Getlocalhost (): Returns the InetAddress object that represents the local host

Getbyname (String hostName): Returns an object by host name

GetAddress (): Return IP Address

GetHostName (): Obtain the host name represented by the IP address

13.TCP Socket Programming

Two Java programs enable data exchange through a two-way network communication connection, one end of the bidirectional link is called a socket (the socket is typically used to connect between client servers)

The two class sockets and ServerSocket in the java.net package are used to implement both the client and the server

A. Service-side (ServerSocket) Authoring steps:

1). Use ServerSocket to establish a port on the service side of the monitoring

2). Create the server socket using the Accept method

3). Create an input-output stream with an established socket

4). Turn off the input/output stream, close the socket, close the server

B. Client side (Socket) Writing steps:

1). Create a client socket to initiate a connection request to the server

2). Create an input-output stream with an established socket

3). Turn off the input/output stream, close the socket, close the server

14.UDP Socket Programming

A. User Message Protocol (UDP) is a non-connection protocol used to send binary data from one computer to another

B. Both the sender and receiver of the datagram package use the Java.net.DatagramSocket class to send and receive packets separately

The Send () and receive () Methods of the C.datagramsocket class have a datagrampacket parameter. The Datagrampacket class represents a datagram packet, similar to Datagramsocket, which is used by both the sender and the recipient of the package.

D. The following steps need to be taken to receive the datagram packet:

1). Create a byte array that is large enough to store the data for the package to be received

2). Instantiate a Datagrampacket object with this byte array

3). Datagramsocket is instantiated, which specifies a port on the local host to which the socket is bound

4). Call the Receive () method of the Datagramsocket class to pass the Datagrampacket object into the method. This causes the execution thread to block until a datagram packet is received or a timeout occurs

E. Sending a datagram packet requires the following steps:

1). Create a byte array that is large enough to store the packet data to be sent and populate the array with that data

2). Create a new Datagrampacket object that stores the byte array above, along with the server name and the recipient's port number

3). Datagramsocket is instantiated and it is specified which port the socket is bound to on the local host

4). The Send () method of the Datagramsocket class is called, passing in the Datagrampacket object

Example: Simple LAN chat system-LAN QQ:

Server-side

Enable easy start-stop server-side operations, record basic logs: Customer connections, messaging, and the ability to view the nickname of the connected customer.

After starting the server, listen for the client connection and create a new thread to implement the listening operation.

Start a new thread listener client

New Thread (New Runnable () {

public void Run () {

Writelog ("Start listening client:");

Listen ();

}

}). Start ();

Open a new thread for each client connection to process traffic, including processing the input and output streams.

Each monitor hears a client connection, initiates a new thread to process the connection

New Participant (this, socket, userslist). Start ();

Get different actions for the user to implement various operations String flag = In.readutf ();

Get user Action behavior

if ("ValidateUser". Equals (flag)) {//Verify that the user exists

........................

} else if ("NewUser". Equals (flag)) {//new user Login

........................

} else if ("message". Equals (flag)) {//Send messages between users

........................

} else if ("UserList". Equals (flag)) {//Get user list

........................

}

On the server side, use map to save the corresponding sockets for each client:

Private map<string, socket> userslist = new hashmap<string, socket> ();

Key is the user nickname entered when the client connects, value is the corresponding socket object.

When a message is sent between client users, the message is forwarded through the server:

String sender = In.readutf (); Sent by

String receiver = In.readutf (); Receiver

String message = In.readutf (); News

Add log

Server.writelog (sender + "to" + Receiver + "Send message:" + message);

The server forwards the message to the target, first obtaining the target socket object to be forwarded

Socket socket = server.getuserslist (). get (receiver);

System.out.println (out);

if (socket = = NULL) {//the server has deleted the client connection information

Out.writeutf ("message");

OUT.WRITEUTF ("System Server");

OUT.WRITEUTF (receiver + "exited system, no more messages sent");

Out.flush ();

} else {

DataOutputStream thatout = new DataOutputStream (Socket.getoutputstream ()); Creating an output Stream object

if (thatout! = null) {

Thatout.writeutf ("message");

Thatout.writeutf (sender);

THATOUT.WRITEUTF (message);

Thatout.flush (); Writes to the client output stream

}

}

Client

The login form is first implemented for server-side connection, and then the login user nickname is entered, if the nickname has not been saved on the server side, the login succeeds. After successful login, you can read the nickname of the logged-on user directly to the server and display to the list. Double-click any item in the Friends list to open the Chat dialog box, and then both parties can start chatting.

Create a socket object to the server:

Creating a Socket Object

Socket = new Socket (Serverip.gettext (). Trim (), Integer.parseint (Port.gettext (). Trim ()));

The connected server and port are obtained from the form text box.

After the login is successful, send the nickname to the server to save:

Out.writeutf ("NewUser");

Out.writeutf (nickname); Out.flush ();

Refresh your friends list:

Reading information from a stream

String flag = In.readutf ();

if ("UserList". Equals (flag)) {//Buddy list

string[] userlist = In.readutf (). Split ("::::"); Get friends list, use tags to separate

Create a buddy list model

Defaultlistmodel list = new Defaultlistmodel ();

for (int i = 0; i < userlist.length; i++) {

List.addelement (Userlist[i]);

}

Friends.setmodel (list); Setting up the Model

Friends.validate (); Redraw

}

Send a message to a friend:

Out.writeutf ("message");

Out.writeutf (sender);

Out.writeutf (recipient);

Out.writeutf (Textarea.gettext ());

Out.flush ();

Turn on new thread to read the friend information forwarded by the server:

String flag = In.readutf ();

if ("Message". Equals (flag)) {

String sender = In.readutf ();

String msg = In.readutf ();

String message = Sender + "Say to You:" + msg + "\ n";

Jtextarea.append (message);

}

Multithreaded programming and Java Network programming

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.