继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Socket总结相关实现(传输对象和传输文件)

showball
关注TA
已关注
手记 5
粉丝 13
获赞 121
客户端传输对象

//建立User类

public class User implements Serializable {
     private String userName;
     private String userId;
     public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public User(){};
     public User(String userName,String userId){
         this.userName=userName;
         this.userId=userId;
     };
}
客户端相关代码
OutputStream os = socket.getOutputStream();// 字节输出流
            PrintWriter pwPrintWriter = new PrintWriter(os);// 将输出流包装成打印流
            ObjectOutputStream oos = new ObjectOutputStream(os);
            // pwPrintWriter.write("用户名:Tom;密码:783");//传入字符串
            User user = new User("Tom", "783");// 传入对象
            oos.writeObject(user);
            pwPrintWriter.flush();
            socket.shutdownOutput();
服务器端相关代码
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
User user = (User) is.readObject();
System.out.println("我是服务器,客户端说" + user.getUserName() + ":"
        + user.getUserId());
socket.shutdownInput();// 关闭输入流
outputStream = socket.getOutputStream(); 
服务器端传输文件,建立File文件夹,里面放置File/UDPClient.txt文件
            file = new File("File/UDPClient.txt");
            fin = new FileInputStream(file);
            byte[] sendByte = new byte[1024];       
            ObjectOutputStream obj=new ObjectOutputStream(outputStream);
            int length;
            while ((length = fin.read(sendByte, 0, sendByte.length))!=-1) {
                obj.write(sendByte, 0, length);
                obj.flush();
            }
客户端接收文件,并进行写出文件
            ObjectInputStream din =new ObjectInputStream(inputStream);      
            FileOutputStream fos = new FileOutputStream("File/UDOClient1.txt"); 
            byte[] buf=new byte[1024];
            int len;
            while ((len = din.read(buf,0,buf.length)) != -1) {
                fos.write(buf, 0, len);
                fos.flush();
            }
            fos.close();
            socket.shutdownInput(); 
打开App,阅读手记
21人推荐
发表评论
随时随地看视频慕课网APP