guan8910
guan8910
2015-04-15 13:36
采纳率: 100%
浏览 1.8k
已采纳

求一个例子:java socket 采用ObjectInputStream序列化收发文件例子

求一个:java socket 采用ObjectInputStream序列化收发文件例子
求一个:java socket 采用ObjectInputStream序列化收发文件例子

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • guan8910
    guan8910 2015-04-16 09:33
    已采纳

    我参考 这个 例子 解决我的问题 http://bbs.csdn.net/topics/200033850

    点赞 评论
  • caozhy
    点赞 评论
  • guan8910
    guan8910 2015-04-16 00:59

    这不是我想要的 你给的这个例子类似的挺多的

    点赞 评论
  • wojiushiwo945you
    毕小宝 2015-04-16 01:32

    楼上正解。就是Socket编程的基础知识,找个例子练习练习就熟悉了。
    按你的要求,给个简单的对象序列号数据发送的例子,执行一遍就了能了解Socket的基本用法了。祝好。
    SocketClient.java和SocketServer.java如下:

     import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.util.Date;
    
    public class SocketClient {
    
        public void send(){
            InetSocketAddress address = new InetSocketAddress("localhost",8005);
            Socket socket = new Socket();
            try {
                socket.connect(address, 2000);
    
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                Date date = new Date();
                out.writeObject(date);
                out.flush();
                System.out.println("Client send data finished.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            new SocketClient().send();
        }
    }
    
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class SocketServer {
        private ServerSocket serverSocket;
    
        public void receive(){
            while(true){
                try {
                    serverSocket = new ServerSocket(8005);
                    Socket socket = serverSocket.accept();
                    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                    Object date = in.readObject();
                    System.out.println("Server received data:"+date.toString());
                    break;
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            new SocketServer().receive();
        }
    }
    
    点赞 评论

相关推荐