客户端传输对象
//建立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();