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

求教socket读写集合问题~~
服务端:
Java code

        public void showById() throws IOException   
        {   
            //接收客户端传来的商品ID   
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));    
   String goodsid1=br.readLine();   
   int goodsid = Integer.parseInt(goodsid1);   
System.out.println(goodsid);   //可以读出
 ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());   
//遍历集合   
for(int i = 0 ; i< goodsData.size(); i++)   
{   
ShopGoods sg = goodsData.get(i);   
//查询单品   
if(sg.getGid()==goodsid)   
{   
oos.writeObject(goodsData);    
System.out.println("ssssssssss");           //此行读不出
}   
}   
}  



客户端:
Java code

public void getGoodsTable() throws IOException,   
ClassNotFoundException   
{   
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));   
System.out.println("请输入您要查询的商品编号:");   
goodsid = br.readLine();   
bw.write(goodsid);   
bw.flush();   
bw.close();   
br.close();   
System.out.println("商品编号"+"\t\t"+"商品名称"+"\t\t"+"商品单位"+"\t\t"+"商品价格"+"\t\t"+"商品数量");        
ois = new ObjectInputStream(s.getInputStream());           
ArrayList<ShopGoods> goodsData =(ArrayList<ShopGoods>)ois.readObject();   
for (ShopGoods sg : goodsData) {   
System.out.println(" "+sg.getGid()+"\t\t"+sg.getGname()+"\t"+"     "+   
sg.getGmean()+"\t\t"+"  "+sg.getGprice()+"\t\t"+"  "+sg.getGnum());   
                }   
            }  




客户端报错:socket is closed;

服务端报错:oftware caused connection abort: socket write error;





------解决方案--------------------
就用List传一次,希望能给你点帮助吧:
Server:
Java code

 try{
            ServerSocket ss=new ServerSocket(8090);
            System.out.println("我是服务器,在8090端口监听");
            Socket s=ss.accept();
            //读取客户端的信息
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            User user = (User) ois.readObject();
            System.out.println("name:"+user.getName()+"\npassword"+user.getPassword());
            
                List<String> list = new ArrayList<String>();
                list.add("测试语句");
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());  
            oos.writeObject(list);

        }catch(Exception  ex)
        {
            ex.printStackTrace();    
        }