日期:2014-05-20  浏览次数:20869 次

c/s通信或线程通信问题
先贴代码再说
服务器端代码

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

class   Customer   extends   Object   implements   Serializable
{
String   custName,   custPwd;
}
public   class     AppServer   implements   Runnable
{
//建立一个ServerSocket   对象   ,注意没有初始化
ServerSocket   serverSocket;
Socket   client;
Thread   serverThread;

public   AppServer()
{

try
{ //ServerSocket对象初始化
serverSocket   =   new   ServerSocket(1001);
serverThread   =   new   Thread(this);
serverThread.start();
}
catch   (IOException   e)
{
fail(e,   "不能启动服务器 ");
}
System.out.println( "服务器开始运行..... ");
 
}
public   static   void   fail(Exception   e   ,   String   Str)
{
System.out.println(Str   +   "   .   "   +   e);
}
public   void   run()
{
try
{
while(true)
{
Socket   client   =     serverSocket.accept();
Connection   con   =   new   Connection(client);
}
}
catch   (IOException   e)
{       //调用自定义的fail方法
fail(e,   "没有监听 ");
}
}
public   static   void   main(String[]   args)  
{
//声明一个对象
new   AppServer();
}
}

class   Connection   extends   Thread
{
Socket   netClient;
ObjectInputStream   fromClient;
PrintStream   toClient;
Customer   clientMessage;

static   Vector   vector   =   new   Vector(1,1);
        static   int   messageCount;//To   count   the   total   number   of   messages        
                                                        //stored
        private   int   localMsgCount;//   To   count   local   messages  


public   Connection(Socket   client)
{
netClient   =   client;

try
{
//   用来获得客户端传过来的信息
fromClient   =   new   ObjectInputStream(client.getInputStream());
//   用来向向客户端写出信息
toClient   =   new   PrintStream(client.getOutputStream());
}
catch   (IOException   e)
{
try
{
netClient.close();
}
catch   (IOException   el)
{
System.out.println( "不能建立流     "+   el);
return   ;
}
}
this.start();
}
public   void   run()
{

try
{
clientMessage   =   (Customer)fromClient.readObject();

//toClient.print(clientMessage.custName+ "   Connected ");
//System.out.println(clientMessage.custName);

for(;;)
{
System.out.println( "yes ");
clientMessage   =   (Customer)fromClient.readObject();//(1)
System.out.println( "no ");