客户端传输对象
//建立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();
点击查看更多内容
21人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦