TCP应用之对象流的传输

package com.wet.TCP;

import java.io.*;

/**
 * 所要传输的对象
 *
 * @author Administrator
 *
 */
public class Message implements Serializable {
 private String message;
 private String time;

 public Message() {

 }

 public Message(String messtime, String time) {
  this.message = messtime;
  this.time = time;
 }

 public String getMesstime() {
  return message;
 }

 public void setMesstime(String messtime) {
  this.message = messtime;
 }

 public String gettime() {
  return time;
 }

 public void settime(String time) {
  this.time = time;
 }

 @Override
 public String toString() {
  return "[message=" + message + ", time=" + time + "]";
 }

}

package com.wet.TCP;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * TCP服务器之对象流传输
 */
public class TCPObjectServer {
 public static void main(String[] args) {
  try {
   ServerSocket ss = new ServerSocket(8888); // 建绑定到特定端口的服务器套接字
   Socket s = ss.accept(); // 侦听并接受到此套接字的连接
   ObjectInputStream in = new ObjectInputStream(s.getInputStream());
   Message mess = (Message) in.readObject();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   System.out.println("来自客户端的对象信息:" + mess + sdf.format(new Date()));
   ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
   Message message = new Message("你好服务器", new Date().toLocaleString());
   out.writeObject(message);
   out.close();
   in.close();
   s.close();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}

package com.wet.TCP;

import java.io.*;
import java.net.*;
import java.util.Date;

/**
 * TCP客户端之对象传输流
 *
 * @author Administrator
 *
 */
public class TCPObjectClient {
 public static void main(String[] args) {
  try {
   // 创建一个流套接字并将其连接到指定 IP 地址的指定端口号
   Socket s = new Socket("127.0.0.1", 8888);
   ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
   Message mess = new Message("你好服务器", new Date().toLocaleString());
   out.writeObject(mess);
   ObjectInputStream in = new ObjectInputStream(s.getInputStream());
   Message message = (Message) in.readObject();
   System.out.println("来自客户端的消息:" + message);
   in.close();
   out.close();
   s.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值