What is a JavaBean? JavaBeans is a software component model. It interacts with other software objects to decide how to build and reuse a software component bean, which is a reusable software component that can be visualized and processed in a programming tool based on sun’s JavaBean specification. Why develop JavaBeans? The requirements of distributed environment for components JavaBeans are portable and can be ported between platforms.
服务器端的程序代码如下:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class MyServer implements Runnable
{
ServerSocket server=null;
Socket clientSocket; //负责当前线程中C/S通信中的Socket对象
boolean flag=true; //标记是否结束
Thread ConnenThread; //向客户端发送信息的线程
BufferedReader sin; //输入流对象
DataOutputStream sout; //输出流对象
public static void main(String[] args)
{
MyServer MS=new MyServer();
MS.ServerStart();
}
public void ServerStart()
{
try
{
server = new ServerSocket(8080); //建立监听服务
System.out.println("端口号:"+server.getLocalPort());
while(flag)
{
clientSocket=server.accept();
System.out.println("连接已经建立完毕!");
InputStream is=clientSocket.getInputStream();
sin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
sout=new DataOutputStream(os);
ConnenThread=new Thread(this);
ConnenThread.start(); //启动线程,向客户端发送信息
String aline;
while((aline=sin.readLine())!=null) //从客户端读入信息
{
System.out.println(aline);
if(aline.equals("bye"))
{
flag=false;
ConnenThread.interrupt(); //线程中断
break;
}
}
sout.close(); //关闭流
os.close();
sin.close();
is.close();
clientSocket.close(); //关闭Socket连接
System.exit(0); //程序运行结束
}
}
catch(Exception e)
{ System.out.println(e); }
}
public void run()
{
while(true)
{
try
{
int ch;
while((ch=System.in.read())!=-1)
{ //从键盘接收字符并向客户端发送
sout.write((byte)ch);
if(ch=='\n')
sout.flush(); //将缓冲区内容向客户端输出
}
}
catch(Exception e)
{ System.out.println(e); }
}
}
public void finalize() //析构方法
{
try
{ server.close(); } //停止ServerSocket服务
catch(IOException e)
{ System.out.println(e); }
}
}