Java Network Programming, java Network Programming pdf

Source: Internet
Author: User

Java Network Programming, java Network Programming pdf

I have been idle recently and have been taking the time to review some Java technical applications.

There is nothing to do today. Based on the UDP protocol, I wrote a very simple chat room program.

Socket is rarely used in current work, which is also a simple record of Java Network Programming.

First look at the effect:

The implementation effect can be said to be very simple, but you can still simply see an implementation principle.

"Chat room 001" users, XiaoHong and Xiaolu chatted with each other. "chat room 002" was ignored and left alone.


Let's take a look at the code implementation:


1. The implementation of the Message Server is simple:

  • Register the client information (which chat room to enter, etc;
  • Construct a UDP socket object to receive messages sent from each client;
  • Parse the message content and push the chat information back to each client in the corresponding chat room;
Package com. tsr. simplechat. receive_server; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. socketException; import java. util. arrayList; import java. util. hashMap; import com. google. gson. gson; import com. tsr. simplechat. bean. messageEntity; import com. tsr. simplechat. client. chatClient; // Chat server public class ChatServer extends Thread {// The program occupies the PORT number private static final int PORT = 10000; // The message receiving socket object private static DatagramSocket server = null; // dictionary object (Key: Chat Room ID, Value: client user set under the chat room); private static HashMap <String, ArrayList <ChatClient> groups = new HashMap <String, arrayList <ChatClient> (); // constructor public ChatServer () {try {// message receiving socket Object Construction initialization server = new DatagramSocket (PORT );} catch (SocketException e) {e. printStackTrace () ;}// register a new user in the chat room public static void logInGroup (String groupID, ChatClient client) {// use the chat room ID, obtain ArrayList <ChatClient> clients = groups for all online users in the chat room. get (groupID); if (clients = null) {clients = new ArrayList <ChatClient> () ;}// register the user who entered the chat room with clients. add (client); // update the chat room information groups. put (groupID, clients);} // receives messages cyclically @ Overridepublic void run () {while (true) {receiveMessage () ;}} private void receiveMessage () {// UDP packet byte [] buf = new byte [1024]; DatagramPacket packet = new DatagramPacket (buf, buf. length); while (true) {try {// accept the data packet server. receive (packet);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} // parse the data packet and obtain the chat information String content = new String (packet. getData (), 0, packet. getLength (); // parse the json data Gson gson = new Gson () through a third-party package; MessageEntity me = gson. fromJson (content, MessageEntity. class); // parse the message content and obtain the ArrayList <ChatClient> clients = groups of all online users in the chat room through the chat room ID. get (me. getGroupId (); // pushes the received message back to the user (ChatClient client: clients) {client. pushBackMessage (me );}}}}

2. The client program is still very simple:
  • Simple definition of the client chat room interface.
  • Construct a socket object for sending messages.
  • Obtain the content of the chat information box and send it to the server.
Package com. tsr. simplechat. client; import java. awt. button; import java. awt. event; import java. awt. frame; import java. awt. textArea; import java. awt. textField; import java. awt. event. windowAdapter; import java. awt. event. using wevent; import java. io. IOException; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; import java.net. socketException; import java.net. unknownHostException; import com. tsr. simplechat. bean. messageEntity; import com. tsr. simplechat. receive_server.ChatServer; // client program public class ChatClient extends Frame {private static final long serialVersionUID = 1L; // chat room IDprivate String groupID; // client user name private String clientName; // client message sending service socket private DatagramSocket msg_send; // service PORT private final int PORT = 10000; // server ip address private InetAddress ip; // client control TextField tf = new TextField (20); TextArea ta = new TextArea (); Button send = new Button ("send "); // client constructor public ChatClient (String groupID, String clientName) {super ("chat room:" + groupID + "/" + clientName); this. clientName = clientName; this. groupID = groupID; // set the client interface style add ("North", tf); add ("Center", ta); add ("South", send ); setSize (250,250); show (); // chat-related server initialization init (); // monitor addWindowListener (new WindowAdapter () {public void windowClosing (LOGIN wevent e) {// close the message sending service msg_send.close (); // close the client program dispose (); System. exit (0) ;}}) ;}// chat-related server initialization private void init () {// register the current user and chat room information and register it with the ChatServer. logInGroup (groupID, this); try {// initialize the message sending socket object msg_send = new DatagramSocket (); // specify the Message Server try {ip = InetAddress. getByName ("127.0.0.1");} catch (UnknownHostException e) {System. out. println ("unknown host exception .. ") ;}} catch (SocketException e) {System. out. println ("socket connection exception .. ") ;}} // message sending button time listener public boolean action (Event evt, Object arg) {if (evt.tar get. equals (send) {try {// obtain the input content String content = tf. getText (); // send the message send_message (content); // clear the chat box tf. setText (null);} catch (Exception ioe) {System. out. print (ioe. getMessage () ;}} return true;} // private void send_message (String content) sent by the message {// message formatting (json format) String message = messageFormat (content ); // encapsulate the message into a UDP packet byte [] buf = message. getBytes (); DatagramPacket packet = new DatagramPacket (buf, buf. length, ip, PORT); try {// send the message msg_send.send (packet) through UDP;} catch (IOException e) {System. out. println ("IO exception .. ") ;}} // message formatting private String messageFormat (String content) {StringBuffer buffer = new StringBuffer (); buffer. append ("{\" groupId \":"). append ("\""). append (groupID ). append ("\", "); buffer. append ("\" userName \":\""). append (clientName ). append ("\", "); buffer. append ("\" text \":\""). append (content ). append ("\"} "); return buffer. toString ();} // obtain the latest message from the server in the current chat room (callback ..) public void pushBackMessage (MessageEntity me) {ta. append (me. getUserName () + ":" + me. getText (); ta. append ("\ n ");}}

3. Message entity class
It is mainly used to encapsulate messages into objects, including chat room ID, message sender nickname, and message content. Use json format for parsing.

Package com. tsr. simplechat. bean; // message entity public class MessageEntity {private String groupId; private String userName; private String text; public String getGroupId () {return groupId;} public void setGroupId (String groupId) {this. groupId = groupId;} public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getText () {return text;} public void setText (String text) {this. text = text ;}}

4. OK. Now we have basically done it. Create a test class.
  • Enable the Message Server.
  • Open three clients, two of which go to "chat room 001" and the other go to "chat room 002 ".
Import com. tsr. simplechat. client. chatClient; import com. tsr. simplechat. receive_server.ChatServer; public class Test {public static void main (String [] args) {ChatServer r = new ChatServer (); r. start (); ChatClient c1 = new ChatClient ("001", ""); ChatClient c2 = new ChatClient ("001", ""); chatClient c3 = new ChatClient ("002"," ");}}

Source code


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.