快速业务通道

用Java Socket制作广播信使程序 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-23
Area 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连接。

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号