Java Network Programming and simple chat programs

Source: Internet
Author: User
Tags thread stop

Java Network Programming and simple chat programs

Network Programming technology is one of the mainstream programming technologies in Internet technology. It is necessary to understand some basic operations. This chapter mainly describes network programming, UDP and Socket programming, and a simple chat software using Socket.


Download all code: Link

1. Network Programming Overview:

Network Programming is essentially data transmission between two (or more) devices (such as computers. To achieve data transmission between two computers over the Internet, data transmission must satisfy the layer-5 protocols (physical layer, data link layer, network layer, transport layer, and application layer) of the computer network ); of course there may be different classifications, but now it is easy to understand the five-layer model. The first three layers of physical layer, data link layer, and network layer cannot be directly controlled by java programmers. The Network Programming mentioned in this chapter is in the transport layer and application layer. For more information about the Internet protocol, see my blog.
1. the transport layer mainly has two Protocols: TCP and UDP. TCP performs reliable connections through the handshake protocol, while UDP is unreliable connections.
2. the application layer directly interfaces with applications and provides common network application services. The main protocols include HTTP, FTP, and DNS.
3. IP Address: Use and mark the ID card of a computer. Note that the Network Address Translation Technology NAT exists. Our personal computers are basically dedicated network IP addresses (192.168..), This IP address can only be accessed by a local computer. Only when we have a public IP can our computers be accessed by all the computers connected to the Internet in the world.
4. service port: The computer uses different service ports to differentiate different network services, just like process numbers to differentiate different processes. Common Service ports: HTTP (80 ), FTP (21 ).
5. URL: a uniform resource identifier. Only Internet resources can be located.

URL basic format: protocol: // hostname: port/resourcename # anchorprotocol: the protocol used. It can be http, ftp, news, telnet, and other hostname: Host Name port: port number. Optional resourcename: resource Name: the directory or file anchor that can be accessed on the host: tag. Optional. The location of a specific tag in the specified file, such as http: // localhost: 8080/HttpSer/index.html.

The following describes network programming through UDP and socket programming;

2. UDP programming Introduction: Overview:
User Data Protocol (UDP) is a low-cost communication method similar to sending short messages, because no dedicated connection is required, the pressure on the server is much lower than that on TCP. It is a protocol that can be transmitted as reliably as possible. It is mainly used for video phones and other applications that do not require high speed of information transmission. Main categories:
DatagramSocket:
The initramsocket class implements "network connection", including client network connection and server network connection. Although UDP-based network communication does not require a dedicated network connection, after all, it still needs to send and receive data. mongoramsocket implements the transmitter when sending data, and the listener role when receiving data
DatagramPacket:
The DatagramPacket class encapsulates the data transmitted over the network. That is, the objects of this Class represent the data exchanged over the network. In UDP-based network programming, both the data to be sent and the data to be received must be processed as a DatagramPacket object, this object contains the address, port number, and content to be sent. A simple udp communication:
Client:
DatagramSocket ds = null; // defines a UDP to send data ds = new DatagramSocket (); // assume that the sent data is a String hello = hello world; // define a UDP data transmission package to send data. inetSocketAddress indicates the address to be received, namely, DatagramPacket dp = new DatagramPacket (hello. getBytes (), hello. getBytes (). length, new InetSocketAddress (127.0.0.1, 9999); for (int I = 0; I <10; I ++) {// data transmission ds. send (dp); // Thread sleep for 1 s Thread. sleep (1000 );}

Server:

DatagramSocket ds = null; // UDP receiver connection ds = new DatagramSocket (9999 ); // define the location where the UDP data packet is received. byte [] buf = new byte [1024]; // define the UDP data receiving package; DatagramPacket dp = new DatagramPacket (buf, buf. length); while (true) {// receives data packets ds. receive (dp); // convert and output data: String str = new String (dp. getData (), 0, dp. getLength (); System. out. println (str );}
3. socket programming Introduction: socket introduction:
Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.
TCP, short for Tranfer Control Protocol, is a connection-oriented Protocol that ensures reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data. Main categories:
1. Create a server class: ServerSocket
You can use the port number required by the server as a parameter to create a server object:
ServerSocket serverSocket = new ServerSocket (8888)
This statement creates a server object that uses port 8888. When a client program establishes a Socket connection with the port number 8888, the server Object server responds to the connection and the server. accept () method creates a Socket object. The server can use this Socket object to communicate with the customer.
// Listen. When no data is sent from the client, stop here; Socket s = serverSocket. accept ();

2. Communication: Socket
The server and client can communicate through the Socket class:
The process of creating a socket class on the client:

// Create a socket client: the first parameter: IP address; the second parameter: The sending port. If there is no server, it will stop here and throw an exception. Socket socket = new Socket (192.168.1.105, 8888 );

The socket class can be used to obtain the input and output streams for communication:

// Obtain the output stream PrintWriter out = new PrintWriter (socket. getOutputStream (); // obtain the socket input stream BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
A simple Socket communication:
Client:
Public static void main (String [] args) {Socket socket = null; PrintWriter out = null; BufferedReader in = null; try {// create a socket Client: first parameter: IP address; second parameter: The sending port. If there is no server, it will stop here and throw an exception. socket = new Socket (192.168.1.105, 8888 ); // obtain the local socket port System allocated by the local machine. out. println (local port: + socket. getLocalPort (); // obtain the local socket port System allocated by the local machine. out. println (remote port: + socket. getPort (); // obtain socketAddress System. out. println (Remote adress: + socket. ge TRemoteSocketAddress (); System. out. println (local adress: + socket. getLocalSocketAddress (); // obtain inetAddress System. out. println (Remote inetAddress: + socket. getInetAddress (); System. out. println (local inetAddress: + socket. getLocalAddress (); // get the output stream of the socket out = new PrintWriter (socket. getOutputStream (); // obtain the socket input stream in = new BufferedReader (new InputStreamReader (socket. getInputStream (); // sends data out. println (peace );/ /Refresh to send out immediately. flush (); // String str = null; // This operation will always wait for the server to send a data; str = in. readLine (); System. out. println (received: + str);} catch (UnknownHostException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {// close the connection if (socket! = Null) {try {socket. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}

Server:

Public static void main (String [] args) {ServerSocket serverSocket = null; PrintWriter out = null; BufferedReader in = null; Socket s = null; int I = 0; try {// create a server: Create a serversocket serverSocket = new ServerSocket (8888); while (true) {try {// listener. When no data is sent from the client, stop here; s = serverSocket. accept (); // obtain the local socket port System allocated by the local machine. out. println (local port: + s. getLocalPort (); // obtain the local socket port System allocated by the local machine. out. println (remote port: + s. getPort (); // Obtain socketAddress System. out. println (Remote adress: + s. getRemoteSocketAddress (); System. out. println (local adress: + s. getLocalSocketAddress (); // obtain inetAddress System. out. println (Remote inetAddress: + s. getInetAddress (); System. out. println (local inetAddress: + s. getLocalAddress (); // get the output stream of the socket. When the socket is closed, the output input of the socket is automatically closed and left out = new PrintWriter (new OutputStreamWriter (s. getOutputStream (); // obtain the output stream of the socket. When the socket is disabled The output input of the socket is automatically closed and left in = new BufferedReader (new InputStreamReader (s. getInputStream (); // output the data sent from the client: String str = null; str = in. readLine (); System. out. println (received + str); out. println (hello + I ++); out. flush ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {if (s! = Null) {s. close () ;}}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {if (serverSocket! = Null) {try {serverSocket. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}
4. Use socket to create a simple chat program:

This chat process can be used to chat with a specified friend or group chat. It is just a simple demonstration.
1. Client
Number of threads: two. One main thread is used to send messages, and one thread is used to receive messages sent by the server.
Single chat implementation: Judge by single sign.
Exit implementation: control up input: quit will prompt to exit
Single chat exit implementation: After Entering single chat, enter q in the console to exit the single chat
2. Server:
Number of threads: determined by the client. After the client type a name, a thread is started to process various client requests and send data. Put all threads into the map set. The key is the user name and the value is the thread object;
Single chat implementation: After receiving the singl mark from the client, use sin to true to implement Single chat, and get the thread of the specified user to send data.
Exit implementation: when receiving the quit sent by the client, send disconnect to the client to disconnect and close the thread.
Single chat Exit: Set the single chat flag to false;
3. The client code is as follows:

Package com. rlovep. clinet; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. printWriter; import java. io. unsupportedEncodingException; import java.net. socket;/***** @ ClassName: TalkClinet * @ Description: chat client: * @ author peace w_peace@163.com * @ date 15 Oct 2015 7:21:22 */public class TalkClinet {// get the console input private BufferedReader sysin = null; // Socket private Socket s = null; private BufferedReader in = null; private PrintWriter out = null; // The thread stops flag private boolean flag = true; // single chat mark private final static String single = single; public static void main (String [] args) {// start the client: new TalkClinet (). start ();}/***** @ Title: start * @ Description: main function: start the sending and receiving tasks * @ return: void * @ throws * @ author peace w_peace@163.com */public void sta Rt () {try {// obtain the System input: sysin = new BufferedReader (new InputStreamReader (System. in, UTF-8); // set the name to System. out. println (enter the user name :); String name = sysin. readLine (); // create the client socket s = new Socket (127.0.0.1, 8888); // obtain the socket output out = new PrintWriter (s. getOutputStream (), true); out. println (name); // obtain the socket input in = new BufferedReader (new InputStreamReader (s. getInputStream (); // creates a receiving thread. Blocks the main Thread new Thread (new ClinetThread ()). start (); // send a message: String str = null; while (flag & (str = sysin. readLine ())! = Null) {// determines whether it is a single chat sign. If it is not a single chat, send a group message if (single. repeated signorecase (str) {System. out. println (enter who you want to talk to :); // obtain the system input: if (flag & (str = sysin. readLine ())! = Null) {// send a chat mark out. println (single) ;}/// the content sent to the server: out. println (str) ;}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {// close the resource if (sysin! = Null) {try {sysin. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} if (s! = Null) {try {s. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}} private class ClinetThread implements Runnable {/***** @ Title: recive * @ Description: receives a message and exits when the message is disconnect, to terminate the system input, press enter once. * @ return: void * @ throws * @ author peace w_peace@163.com */private void recive () {try {// receive Server Message String str = in. readLine (); if (str! = Null) {// if the chat ends, the thread if (disconnect. equals (str) {stop (); System. out. println (Press enter to exit :);} else {// otherwise, the message System is displayed. out. println (str) ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/// thread stop method public void stop () {flag = false;} // main thread task @ Override public void run () {while (flag) {// call recive () ;}}} to receive the message function ();}}}}

4. The server code is as follows:

Package com. rlovep. server; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. printWriter; import java.net. serverSocket; import java.net. socket; import java.net. socketException; import java. util. hashMap; import java. util. map; public class TalkServer {// Save the chat thread: private Map
  
   
Map = new HashMap
   
    
(); Public static void main (String [] args) {// start the server new TalkServer (). start ();}/***** @ Title: start * @ Description: creates an independent thread for each client * @ return: void * @ throws * @ author peace w_peace@163.com */public void start () {// server servesocket ServerSocket serverSocket = null; // server socket Socket socket = null; try {// server create serverSocket = new ServerSocket (8888); // an endless loop, used to receive more clients while (true) {// create socket = serverS for chat threads Ocket. accept (); // create a service thread for each client. ServerThread st = new ServerThread (socket); new Thread (st ). start () ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {// release resource try {if (serverSocket! = Null) {serverSocket. close () ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}/ ***** @ ClassName: ServerThread * @ Description: chat thread * @ author peace w_peace@163.com * @ date 15 Oct 2015 8:31:44 */private class ServerThread implements Runnable {// corresponding socket private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; // name of each chat private String name = null; // chat header private String meshead = null; // stop the thread flag private boolean flag = true; // single chat flag: private boolean sin = false ;/****
    

Title: thread Constructor

*

Description: used to create a thread, initialize the thread, and add the thread to the map.

* @ Param socket * @ throws IOException */public ServerThread (Socket socket) throws IOException {// obtain socket this. socket = socket; // get the output and input out = new PrintWriter (socket. getOutputStream (), true); // get the username word in = new BufferedReader (new InputStreamReader (socket. getInputStream (); name = in. readLine (); System. out. println (name + online); // create the chat header meshead = name + [+ socket. getInetAddress (). getHostAddress () +: + socket. getPort () +]; // Add the thread to map: the key is the name; the value is the thread map. put (name, this); // remind all users to send (meshead + online);}/***** @ Title: send * @ Description: send messages (Group) * @ param msg * @ return: void * @ throws * @ author peace w_peace@163.com */public void send (String msg) {// iterative mass for (ServerThread thread: map. values () {thread. out. println (msg) ;}}/***** @ Title: Cycler * @ Description: receives the message and forwards the * @ throws IOException * @ return: void * @ aut Hor peace w_peace@163.com */public void javaser () throws IOException {String str = null; ServerThread qq = null; // receives the message while (str = in. readLine ())! = Null) {// if the message is quit, exit if (quit. equalsIgnoreCase (str) {stop (); // send the close link command out to the client. println (disconnect); break;} // determines whether it is a single chat if (sin = false) {if (str. equals (single) {// if it is a single chat, you will get the user you want to chat with. if (str = in. readLine ())! = Null) {// obtain another client thread qq = map. get (str); if (qq! = Null) sin = true;} else {// send (meshead + str) in a batch by forwarding a message;} // send a message to the corresponding client for a single chat; else {// exit single chat if (str. equals (q) {sin = false; qq. out. println (name + end of the conversation);} // otherwise, the else qq message is sent. out. println (name +: + str) ;}}/ ***** @ Title: stop * @ Description: stop function * @ return: void * @ throws * @ author peace w_peace@163.com */public void stop () {flag = false; // remove code map offline; map. remove (name); send (meshead + is offline );}/** * Run Method */@ Override public void run () {try {while (flag) {// keep receiving the Message Receiver () ;}} catch (SocketException e) {stop (); // error caused by direct client shutdown;} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} finally {// release resource try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}}

 

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.