receptacal和socket tcp udp区别的区别

[转载]Java&Socket通信中传递Object对象
1:对象实现Serializable接口时,保证serialVersionUID一致:
private static final long serialVersionUID =
-1888097L;
import java.io.IOE
import java.io.ObjectInputS
import java.io.ObjectOutputS
import java.net.ServerS
import java.net.S
public class Main {
& & private static final int
PORT = 7777;
& & private Socket
& & private ServerSocket
& & public Main() throws
IOException {
& serverSocket = new ServerSocket(PORT);
& while (true) {
& & & socket =
serverSocket.accept();
DoService(socket);
& & class DoService extends
& private S
& public DoService(Socket socket) {
this.socket =
& public void run() {
& & // 读取客户端发送来的student对象
& & ObjectInputStream ois = new
ObjectInputStream(socket.getInputStream());
& & Student student = (Student)
ois.readObject();
& & String vReceptMsg = "you send
student - id: " + student.getId() + " &name: " +
student.getName();
System.out.println(vReceptMsg);
& & // 向客户端发送新的对象
& & int vNewId = student.getId()
& & String vNewName = "李四" +
& & student.setId(vNewId);
student.setName(vNewName);
& & ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
oos.writeObject(student);
& & oos.flush();
& & & } catch
(IOException e) {
& & e.printStackTrace();
& & & } catch
(ClassNotFoundException e) {
& & e.printStackTrace();
& & public static void
main(String[] args) {
& } catch (IOException e) {
e.printStackTrace();
import java.io.IOE
import java.io.ObjectInputS
import java.io.ObjectOutputS
import java.net.S
import java.net.UnknownHostE
public class Main {
& &private static final
String IP = "127.0.0.1";
& & private static final int
PORT = 7777;
& & public Main() throws
UnknownHostException, IOException, ClassNotFoundException {
& Socket client = new Socket(IP, PORT);
& // 向服务器端发送学生对象
& ObjectOutputStream oos = new
ObjectOutputStream(client.getOutputStream());
& Student student = new Student();
& student.setId(001);
& student.setName("Mary");
& oos.writeObject(student);
& oos.flush();
& // 服务器端返回的新学生数据
& ObjectInputStream ois = new
ObjectInputStream(client.getInputStream());
& Student newStudent = (Student)
ois.readObject();
& String vReceptMsg = "you get student - id: " +
newStudent.getId() + " &name: " +
newStudent.getName();
& System.out.println(vReceptMsg);
& & public static void
main(String[] args) {
& } catch (UnknownHostException e) {
e.printStackTrace();
& } catch (IOException e) {
e.printStackTrace();
& } catch (ClassNotFoundException e) {
e.printStackTrace();
Student类:
import java.io.S
public class Student implements Serializable {
private static final long serialVersionUID =
-1888097L;
& & private String
& & public int getId()
& & public void setId(int
& this.id =
& & public String getName()
& & public void
setName(String name) {
& this.name =
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 recept 的文章

 

随机推荐