服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

用java socket制作广播信使程序


  简介

  java是一个强大的面向对象开发语言,支持很多功能,比如,通过socket编程达到的c/s通讯,基于windows的编程,基于console的编程,还有数据库连接,图象和声音编程等。 java多用在基于internet的网络编程上,创建一些嵌入到html页面中的applet小程序来实现。

  在开始实际编写代码之前,为了使得概念更加清晰,需要提及几个重要的概念。广播信使(broadcast messenger)是要创建一个服务器,用来负责接收和响应来自客户机的网络消息。这个就叫做广播(broadcasting),意思是发送数据包或者消息到所有的客户机。

  这里使用的是服务器/客户机(c/s)框架,因为有一台计算机扮演服务器的角色来响应客户机的消息,所有其他的计算机都扮演客户机的角色,仅仅只是发送请求到服务器来执行它们的一些任务。socket是连接计算机彼此的一个逻辑连接。要创建一个socket,需要提供一个端口号和一个主机ip地址/主机名。

  多线程意味着一个进程的多个线程能够同时运行在分配给它们的同一个处理器上,就感觉好象只有进程在运行。所以,通过多线程技术,许多客户机可以连接服务器的同一个端口。线程是占有资源的进程或程序的一部分,比如文件,i/o等等,它们能够独立运行。

  java代码解释

  首先,我们创建一个服务器,创建一个server和client类,并import下面几个文件:

import java.io.*;
import java.net.*;
import java.awt.*;

  为server类设计一个interface使得从客户机到达的请求能够显示在一个window form里。一个简单server window设计如下:

用java socket制作广播信使程序(图一)
figure 1: 一个服务器窗口,显示所有输入和输出,客户机名和ip地址的日志。


  我们在窗口顶部创建了一个菜单,在中间创建了一个textarea和一个help对话框。我们设置窗口的容器布局管理器为流布局(flowlayout)。这个流布局管理器以行来放置组件,当一行满后,自动将组件换到下一行。在java中也有其他的布局管理器可用,比如border layout manager, grid layout manager, card layout manager, box layout manager, 和gridbag layout manager。下面给出代码:

public class chatserver extends jframe {
 public chatserver(string title) //constructor to initialize the
 //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 for
  //about
  {
   joptionpane opt;
   string name;
   public aboutaction(string name)
   {
    this.name=name;
   }

   //about menu event:
   public void actionperformed(actionevent ae)
   {
    //if(ae.getsource() == aboutaction)
    {

     joptionpane.showmessagedialog(opt,"chitchat_broadcast_messenger/ncopyright
fatima_ahmed","about_chitchat_broadcast_messenger",j
optionpane.information_message);
    }

   }
  }
 

用java socket制作广播信使程序(图二)
figure 2: about对话框

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 (); //calls the accept()
   //method whenever the
   //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");
 }
}

  socket是通过另一个类“chathandler”创建的,是包含在demo project文件中。现在,我们设计一个client类:

用java socket制作广播信使程序(图三)
figure 3: client信使窗口询问每次连接初始化的用户登陆名

用java socket制作广播信使程序(图四)
figure 4: 一个客户机窗口,包含一些字体,颜色选取框和一个菜单来控制窗口。


  在client类中导入以下文件。我们已经创建了另一个类“sketchframe”,它是用来定义一些客户机窗口的interface的。我们描叙一下java中的socket类的一些基本功能,并在客户端线程上实现了start ( ), run ( ),和stop ( )方法。这个类有以下导入的文件:

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 the
 //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);
 }
}

  当用户运行程序并在输入框中输入一些信息,然后回车后,start ( )方法就被调用,并创建了一个socket来初始化输入流和输出流,发送在客户端输入的消息给服务器,服务器再广播这个消息到其他客户端。只要对话建立,那么run ( )将被调用,并发送消息。当用户退出程序时,stop ( )方法被调用,并关闭socket连接。

扫描关注微信公众号