用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 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
关于用Java Socket制作广播信使程序 - 编程入门网的所有评论