本文主要是介绍服务器客户端间数据传输(最简单例子),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
服务器客户端间数据传输(最简单例子)
本地Send项目向Re项目传输数据
项目结构如下:
Send
项目为发送数据,Re
项目为接收数据
由于需要实体所以两个项目要有同样的实体类Student
Student.java
(两个Student
类代码完全相同)代码如下:
import java.io.Serializable;public class Student implements Serializable {private int age;public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
Send.java
代码如下:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;public class Send {public static void main(String[] args) {try {// 本地主机 端口8001Socket s = new Socket("localhost", 8001);// 获取输出流OutputStream os = s.getOutputStream();// Student对象Student stu = new Student();// 写入学生年龄20stu.setAge(20);// 对象输出流ObjectOutputStream oos = new ObjectOutputStream(os);// stu对象写入oos输出流oos.writeObject(stu);// 清空oos流oos.flush();// oos os s 分别关闭oos.close();os.close();s.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
Recive.java
代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;public class Recive {public static void main(String[] args) {try {// 创建一个ServerSocket套接字对象,并绑定在8001端口上ServerSocket ss = new ServerSocket(8001);// 连接成功 将ss返回的Socket接收Socket s = ss.accept();// 输入流InputStream is = s.getInputStream();// 对象输入流ObjectInputStream ois = new ObjectInputStream(is);// 将对象从流中取出来Student stu = (Student) ois.readObject();// 输出年龄System.out.println(stu.getAge());// 关闭流ois.close();is.close();s.close();ss.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
运行时,先运行Recive.java
再运行Send.java
结果如下:
这篇关于服务器客户端间数据传输(最简单例子)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!