A simple chat room written in Java to learn the socket programming __ algorithm

Source: Internet
Author: User
Tags reserved

/* *create on 2009 *copyright 2009 Quasar20063501.all Rights reserved * *weizhaozhe client; Import java.awt.*; Import java.awt.event.ActionEvent; Import Java.awt.event.ActionListener; Import Java.awt.event.WindowAdapter; Import java.awt.event.WindowEvent; Import Java.io.DataInputStream; Import Java.io.DataOutputStream; Import java.io.IOException; Import java.net.*; public class ChatClient extends Frame {Private Boolean connected = false; private DataOutputStream dos = null; private Da Tainputstream dis = null; Private static final long serialversionuid = 1L; Private Socket s = null; Private TextField tfwords = null; Private TextArea tashow = null; public static void Main (String args[]) {chatclient cc = new ChatClient (); Cc.launchframe (); cc. Listen (); public void Launchframe () {try {s = new Socket (Inetaddress.getbyname ("localhost"), 8888); connected = true; dos = new DataOutputStream (S.getoutputstream ()); dis = new DataInputStream (S.getinputstream ()); catch (IOException IoE) {System.out.println ("Server connection failed.") "); Ioe.printstacktrace (); } this.tfwords = new TextField (); This.tashow = new TextArea (); This.settitle ("Chatroom Client"); This.setlocation (700, 50); This.add (Tfwords, Borderlayout.south); This.add (Tashow, Borderlayout.north); This.setsize (200, 250); This.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {try {connected = false; Dos.write UTF ("# # #Exit ###"); Dos.flush (); Close (); System.exit (0); The catch (IOException IoE) {System.out.println ("message send error. "); Ioe.printstacktrace (); } } }); This.setvisible (TRUE); This.tfWords.addActionListener (New Tfwordslistener ()); public void Listen () {New Thread () (New Listenthread ()). Start (), public void Close () {try {if (Dos!= null) dos.close ( ); if (s!= null) s.close (); catch (IOException IoE) {ioe.printstacktrace (); SYSTEM.OUT.PRINTLN ("Error occurred while client was disconnected.") "); System.exit (-1); The public class Listenthread implements runnable{public void run () {while (connected) {try {Stringback = Dis.readutf (); Block IO tashow.append (back); }catch (socketexception se) {System.out.println ("Thank you for using.") "); } catch (IOException e) {System.out.println ("data loss.") "); E.printstacktrace (); Private class Tfwordslistener implements ActionListener {public void actionperformed (ActionEvent e) {String word s = Tfwords.gettext (). Trim (); Tashow.append ("ME:" + words + "n"); Tfwords.settext (""); try {dos.writeutf (words);} catch (IOException IoE) {System.out.println ("Send an error. "); Ioe.printstacktrace (); The code is as follows:

Server-side:

 /* *create on the *copyright 2009 quasar20063501.all Rights * Reserved/*WEIZHAOZHE server; /** * This chat room program is based on the TCP socket, which, in order to eliminate IO blocking, using a multi-threaded approach. * * * @author Quasar20063501 * @since 2009 * * */import Java.io.DataInputStream; Import Java.io.DataOutputStream; Import java.io.IOException; Import java.net.*; Import java.util.List; Import java.util.ArrayList; public class Chatserver {private list<client> clients = new arraylist<client> (); private Boolean started = FA Lse Private ServerSocket SS = null; Private Client c = null; Public chatserver () {try {ss = new ServerSocket (8888); started = true;} catch (IOException IoE) {System.out.println ("pair No, the server cannot start. "); Ioe.printstacktrace (); System.exit (-1); } public void Start () {try {Socket s = this.getss (). Accept (); System.out.println ("Here Comes a client!"); if (s!= null) {c = this.new Client (s, true); This.clients.add (c); new Thread (c). Start ();//Threads never stop ...? c = null;}} catch (IOException E){System.out.println ("Connection Error"). "); E.printstacktrace (); } public boolean isstarted () {return started.} public void Setstarted (Boolean started) {this.started = started;} pub Lic ServerSocket getss () {return SS;} public void Setss (ServerSocket ss) {THIS.SS = SS; Clients () {return Clients.} public void Setclients (list<client> Clients) {this.clients = Clients;} public static void Main (String args[]) {Chatserver cs = new Chatserver (); while (cs.isstarted ()) {Cs.start ();} Private Class Clien T implements Runnable {Private Boolean connected = false; private Socket s = null; private DataInputStream dis = NULL; PR Ivate DataOutputStream dos = null; Public Client (Socket s, Boolean connected) {THIS.S = s; this.connected = connected;} public void Run () {inetaddress IP = NULL; int port = 9999; try {if (connected) {dis = new DataInputStream (S.getinputstream ()); dos = new DataOutputStream (S.getoutputstream ()); IP = S.getinetaddress (); Port = S.getPort (); while (connected) {String line = Dis.readutf (), if (Line.equals ("# # #Exit ###")) {getclients (). Remove (this);//When the release is received To remove the client record line = "bye-bye!"; connected = false; } System.out.println ("From: (" + ip.tostring () + ":" + Port + "):" + line); for (int i = 0; i < getclients (). Size (); i++) {if this.equals (getclients (). get (i)) {continue;} else {getclients () . get (i). Dos.writeutf ("From: (" + ip.tostring () + ":" + Port + "):" + line + "/n");}}} catch (IOException IoE) {System.out.println ("Client connection error.") "); Ioe.printstacktrace (); } } } }

Overview of SOCKET Network programming:

Socket, also known as sockets, is two programs for two-way data transmission network pass

The end of the letter, generally composed of IP + PORT.

(We program, usually using the port is greater than 1023 of the number less than 65535, 1023 is generally used before, such as 80 by the HTTP service its occupation, 21 by Telnet, 23 by the FTP server occupancy, etc.)

Socket is a low-level communication mechanism, the data through the socket is the original byte stream, must go through the procedures at both ends to deal with and explain.

It is divided into two categories, TCP/IP communication for the connection, and connectionless UDP datagram communication, our chat room is a TCP/IP-oriented connection written.

Using the process, on the server side and the client, using ServerSocket and sockets respectively, the basic process is as follows:

1 Creating sockets

2 Open Connected IO

3 Read and write according to protocol

4 Closing Resources

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.