Use Java Socket to create a broadcast messenger Program

Source: Internet
Author: User

Use Java Socket to create a broadcast messenger Program

Translated by caiyi0903 (willpower), 2004.3.1 

Introduction

Java is a powerful object-oriented development language that supports many functions, such as c/s communication through socket programming, window-based programming, console-based programming, and database connection, image and sound programming. Java is implemented by using Internet-based network programming to create applet embedded in HTML pages.

Before writing code, several important concepts need to be mentioned to make the concept clearer. Broadcast messenger is used to create a server to receive and respond to network messages from clients. This is called broadcast, which means to send data packets or messages to all clients.

The server/client (C/S) framework is used here, because a computer plays the role of a server to respond to client messages, and all other computers play the role of the client, only requests are sent to the server to execute some of their tasks. Socket is a logical connection between computers. To create a socket, you must provide a port number and a Host IP Address/Host Name.

Multithreading means that multiple threads of a process can run on the same processor assigned to them at the same time, as if only the process is running. Therefore, with multithreading technology, many clients can connect to the same port of the server. Threads are part of processes or programs that occupy resources, such as files and I/O. They can run independently.

Java code explanation

First, create a server, create a server and client class, and import the following files:

Import java. Io .*;
Import java.net .*;
Import java. AWT .*;

Design an interface for the server class so that requests arriving from the client can be displayed in a window form. A simple server window is designed as follows:

Figure 1: A server window that displays logs of all inputs and outputs, client names and IP addresses.

We created a menu at the top of the window, and a textarea and a help dialog box in the middle. We set the container layout manager of the window to flowlayout ). The stream layout manager places components in rows. When a row is full, the component is automatically switched to the next row. Other layout managers are also available in Java, such as border layout manager, grid layout manager, card layout manager, box layout manager, and gridbag layout manager. The following code is provided:

Public class chatserver extends jframe {
Public chatserver (String title) // constructor to initialize
// Chatserver class
{
Output = new textarea (15, 40); // output is a textarea component
// Of The chatserver class
Output. seteditable (false );
Output. setfont (f );
Output. setforeground (color. Blue );

Settitle (title); // to set the title of the client window
Setjmenubar (menubar); // to initialize the menu bar on the window
Jmenu filemenu = new jmenu ("file ");
Jmenu colormenu = new jmenu ("color ");
Jmenu helpmenu = new jmenu ("help ");

// Main Menu shortcuts:
Filemenu. setmnemonic ('F ');
Colormenu. setmnemonic ('C ');
Helpmenu. setmnemonic ('H ');

// About dialog init:
Aboutitem = new jmenuitem ("about ");
// Aboutitem. addactionlistener (actionlistener) This );
Helpmenu. Add (aboutitem );
Addmenuitem (helpmenu, aboutaction = new aboutaction ("about "));

// Initialize menu items:
Menubar. Add (filemenu );
Menubar. Add (colormenu );
Menubar. Add (helpmenu );

Enableevents (awtevent. window_event_mask );

Class aboutaction extends abstractaction // creates an abstract
// Internal class
// About
{
Joptionpane OPT;
String name;
Public aboutaction (string name)

{
This. Name = Name;
}

// About menu event:
Public void actionreceivmed (actionevent AE)
{
// If (AE. getsource () = aboutaction)
{

Joptionpane. showmessagedialog
(OPT, "chitchat_broadcast_messenger/ncopyright
Fatima_ahmed "," about_chitchat_broadcast_messenger ", J
Optionpane. information_message );
}

}
}

Figure 2: About dialog box

Public static void main (string ARGs []) throws ioexception {

Chatserver serverwindow = new chatserver ("chitchat Broadcast
Messenger: Server window ");
// Creates an object of server
Toolkit thekit = serverwindow. gettoolkit (); // to create an object
// Of Toolkit
Dimension wndsize = thekit. getscreensize ();

Serverwindow. setbounds (wndsize. width/4, wndsize. Height/4,
Wndsize. width/2, wndsize. Height/2 );
Serverwindow. setvisible (true );
Serverwindow. getcontentpane (). Add ("North", output );
// To add the textarea (output) at the north of the window
Serverwindow. getcontentpane (). setlayout (New flowlayout
(Flowlayout. Center ));
// To set the layout as centrally Flow
Serverwindow. Pack (); // to pack the server window with above
// Initialize Components

If (ARGs. length! = 1)
Throw new illegalargumentexception ("Syntax: chatserver
<Port> ");
Int Port = integer. parseint (ARGs [0]);
String logins;
Serversocket Server = new serversocket (port );
// To create an object for server's socket
While (true ){
Socket Client = server. Accept (); // callthe accept ()
// Method whenever
// Clients request
System. Out. println ("accepted from" +
Client. getinetaddress () +
"With name" + logins );
Chathandler handler = new chathandler (client, yourname );
Handler. Start (); // The broadcasting of messages is
// Started by START () method
Output. append ("/n accepted from" +
Client. getinetaddress () + "/N ");
}
}

The socket is created by using another "chathandler" class and is included in the demo project file ). Now, we design a client class:

Figure 3: the client messenger window asks the user login name for each connection Initialization

Figure 4: a client window that contains fonts, color selection boxes, and a menu to control the window.

Import the following files in the client class. We have created another class "sketchframe", which is used to define interfaces of some client windows. We describe some basic functions of the socket class in Java, and implement the START (), run (), and stop () Methods on the client thread. This class has the following imported files:

Import java. Io .*;
Import java.net .*;
Import java. AWT .*;
Import java. AWT. image .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Import javax. Swing. event .*;

Public class chatclient implements runnable, windowlistener,
Actionlistener, listselectionlistener {
Protected string host;
Protected int port;
Public textarea output;
Protected textfield input;
String yourname;
Sketchframe window;

Public chatclient (string host, int port, sketchframe window ){
// Constructor initializing the chatclient class
This. Host = host; // host and port will be used to open
// Socket
This. Port = port;
This. yourname = joptionpane. showinputdialog ("Enter login name :");
// To create an input dialog box

Window. setsize (100,100); // to set the size of the client
// Window
Window. getcontentpane (). Add (output, borderlayout. center );
// To add textarea (output) at the center of the window
Window. getcontentpane (). Add (input, borderlayout. South );
// To add the textbox (input) at the bottom (South)

Protected datainputstream dataIn;
Protected dataoutputstream dataout;
Protected thread listener;

Public synchronized void start () throws ioexception {
// Thread synchronization method for starting Broadcast
If (listener = NULL ){
Socket socket = new socket (host, Port); // to initialize
// The socket
Try {
DataIn = new datainputstream
(New bufferedinputstream (socket. getinputstream ()));
Dataout = new dataoutputstream
(New bufferedoutputstream (socket. getoutputstream ()));
Dataout. writeutf (yourname + "has loggged on/N ");
}
Catch (ioexception ex)
{
Socket. Close ();
Throw ex;
}
}
Listener = new thread (this );
Listener. Start ();
Window. setvisible (true );
}
}
Public synchronized void stop () throws ioexception
// Thread synchronization method for stopping the Broadcast
{
If (listener! = NULL)
{

Listener. Interrupt ();
Listener = NULL;
Dataout. Close ();
}

Public void run () {// thread method for reading a new message
// Line from the client
Try {
While (! Thread. interrupted ())
{
String line = dataIn. readutf ();
Output. append (LINE + "/N ");
}
}
Catch (ioexception ex)
{
Handleioexception (Ex );
}
}

When the user runs the program and enters some information in the input box, and then press enter, the START () method is called, And a socket is created to initialize the input stream and output stream, the message sent from the client to the server. The server then broadcasts the message to other clients. As long as the dialog is established, run () is called and a message is sent. When you exit the program, the STOP () method is called and the socket connection is closed.

Source code download

Download the demo project-8.67 KB

Translated by caiyi0903 (willpower), 2004.3.1

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.