import java.io.*; 输入输出包
import java.net.*; 网络包
public class chatSvr 定义chatSvr类
{
public static void main(String[] str)
{
ServerSocket soc;
Socket svrSoc; 创建端口
ObjectOutputStream objOut=null;
ObjectInputStream objIn=null; 输入和输出
Try 以下函数可能会出现异常
{
System.out.println("Waiting for client's connecting...");
soc=new ServerSocket(6666); 本机端口6666
svrSoc=soc.accept(); 等待连接
System.out.println("The client connected, you can Exit this program by type 'QUIT'");
objOut=new ObjectOutputStream(svrSoc.getOutputStream()); 输出客户端的内容
objIn=new ObjectInputStream(svrSoc.getInputStream());接受客户端输入的内容
}catch(Exception e){System.exit(0);}
sendMsgOut send=new sendMsgOut(objOut);
send.start();
getMsgFromClient get=new getMsgFromClient(objIn);
get.start();
}
}
class sendMsgOut extends Thread
{
ObjectOutputStream objOut=null;
public sendMsgOut(ObjectOutputStream out)
{
objOut=out;
}
public void run()
{
String strMsg="";
while(true)
{
try{
strMsg=(new BufferedReader(new InputStreamReader(System.in))).readLine();
objOut.writeObject(strMsg);
if (strMsg.equals("QUIT"))System.exit(0);
}catch(Exception e){}
//System.out.println(strMsg);
}
}
}
class getMsgFromClient extends Thread
{
ObjectInputStream objIn;
public getMsgFromClient(ObjectInputStream in)
{
objIn=in;
}
public void run()
{
String strMsg="";
while(true)
{
try{
strMsg=(String)objIn.readObject();
System.out.println("The client said:"+strMsg);
if (strMsg.equals("QUIT"))System.exit(0);
}catch(Exception e){}
}
}
}