一 此次接触socket编程主要是因为需要从硬件端获取传感器数据,利用4G将数据发送到服务器后进行存储。
先在本机进行代码测试,工具有eclipse,mysql,navicat 。
代码部分主要是完成客户端的数据发送,服务端进行数据判别后,然后把数据格式化后存进数据库。
话不多说,放代码
二
客户端
public class test1 {
private static final String host = "127.0.0.1";
//定义端口和ip 本机测试
// private static final int port = 65002;
private static final int port = 8080;
public void connect(String host, int port) {
Socket socket = null;
BufferedReader reader = null;
PrintWriter writer = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
while (true) {
//writer.println("Hello Server, I am test1 " + socket.getInetAddress());
writer.println("gzz:<111111><1111112>{土壤温度传感器id:5.9,土壤湿度传感器id:12.1,土壤电导率传感器id:2.1,空气温度传感器id:5.9,空气湿度传感器id:12.1,光照强度传感器id:2.1,果实大小传感器id:27.9,果实纸条传感器id:7.9,土壤PH传感器id:45.8}fujia"); //此处是要发送的数据,格式大概就是如此
System.out.println("ok");//向服务端发送 数据 并接受服务端返回数据
String response = reader.readLine();
System.out.println("server return message to test1: " + response);
Thread.sleep(3000);// 线程休眠
//System.out.println("111111111");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (reader != null) {//异常处理
reader.close();
}
if (writer != null) {
writer.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
new test1().connect(host, port);
}
服务端:
public class Server {
public static void main(String[] args){
System.out.println("--等待客户端的连接--");
new Server(8080).start();//监听端口 启动服务
}
private int port;
//private ExecutorService service = Executors.newFixedThreadPool(4); //服务端创建线程的数量
private ExecutorService service =Executors.newCachedThreadPool();
public Server(int port) {
this.port = port;
}
public void start() {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(port);
while (true) {
socket = serverSocket.accept();
System.out.println("---客户端已连接---");
service.submit(new ServerHandler(socket));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
String threadName = Thread.currentThread().getName();
String requestName = socket.getInetAddress().getHostName();
String readerInfo = null;
while (true) {
readerInfo = reader.readLine();
if (readerInfo == null) {
break;
}
writer.println(requestName + " 你的请求已处理,处理线程:" + threadName+" "+readerInfo);//在第117行 返回客户端,造成客户端无法正常循环运行 初步考虑代码逻辑问题
matcher.returnMap(readerInfo);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (reader != null) {//*抛出异常 关闭服务
reader.close();
}
if (writer != null) {
writer.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
数据处理部分的封装类
public class matcher {
public static Map returnMap(String readinfor) {
Map k =new HashMap<>();
// String xy="^xy:\\<(.*?)\\,(.*?)\\,(.*?)\\,(.*?)\\,(.*?)\\,(.*?)\\,(.*?)\\,(.*?)\\>(.*?)isU$";
// String chat="^chat:\\<(.*?)\\<(.*?)\\<(.*?)isU$";//利用正则表达式 对数据进行甄别后,利用匹配到的数组结构 把数据进行格式化后在进行存储
String sxy="^sxy:\\<(.*?)\\>\\<(.*?)\\>\\{(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\}\\<(.*?)\\>\\<(.*?)\\,(.*?)\\,(.*?)\\>(.*?)isU$";
String gzz="^gzz:\\<(.*?)\\>\\<(.*?)\\>\\{(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\,(.*?)\\:(.*?)\\}(.*?)fujia$";
Pattern code=Pattern.compile(sxy);
Matcher matcher=code.matcher(readinfor);
if(matcher.find()) {
for (int i=3;i
调用的时间函数
public class date {
public static String puttime() {
Date date=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");//时间的格式
return df.format(date);
}
}
数据的存储
public class connection {
static int i=0;
static String sql = "insert into test1(device_pid,property,value,timestamp) values(?,?,?,?)";
public static String ok(String device_pid,String property,String value,String timestamp) {
Connection connection=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//System.out.println("已经加载了jdbc驱动程序");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/student?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true","root","123321");//数据库连接
System.out.println("已经连接到数据库");
//ResultSet rs = stmt.executeQuery("select * from test1");
PreparedStatement pst = connection.prepareStatement(sql);//用来执行SQL语句查询,对sql语句进行预编译处理
insert(pst,device_pid,property,value,timestamp);
System.out.println("数据已经插入"+i+"条");
i++;
} catch (SQLException e) {
System.out.println("获取数据错误");
e.printStackTrace();
}
if(connection !=null) {
try {
connection.close();
System.out.println("数据库已经关闭");
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
static String insert(PreparedStatement pst,String device_pid, String property, String value, String timestamp){
String flog="success";
try {
pst.setString(1, device_pid);
pst.setString(2, property);
pst.setString(3, value);
pst.setString(4, timestamp);
pst.executeUpdate();//解释在下执行sql语句
} catch (SQLException e) {
e.printStackTrace();
flog ="false";
}
return flog;
}
}
因为要在服务器上运行,所以制作了jar包,制作jar包的过程很简单,利用runnable jar 制作即可,论坛特多。
测试jar包的可用性:
jar包的链接放到云盘,如有错误,请规正。
链接:https://pan.baidu.com/s/1m0a281yy6lwVnnUjUrVsGg 提取码:o164