socket(五)IDEA与socket
在IDEA处,我们完成服务器的任务
main:
首先我们需要在main函数里面创建server
package org.example; import java.io.IOException; import java.security.Provider; public class Main { public static void main(String[] args) throws IOException { Server server = new Server(); } }
server类
在server部分中,我们首先需要定义一些东西
static int port = 8888; ServerSocket serverSocket; List<Socket> list = new ArrayList<>(); BufferedReader in; BufferedWriter out;
在server构造函数中,我们需要创建以serverSocket对象,指定端口号,然后再while循环中接收客户端的请求,每当有客户端连接成功,就创建一个Socket对象,将其添加到列表中,然后创建线程对象,将列表传递给线程,然后启动这个线程。
public Server(){ try { serverSocket = new ServerSocket(port); System.out.println("open server in " + port); } catch (IOException e){ e.printStackTrace(); } while(true){ try { Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress().toString() + ":" + socket.getPort()); list.add(socket); ClientThread clientThread = new ClientThread(socket); clientThread.setSocketList(list); clientThread.start(); } catch (IOException e) { e.printStackTrace(); } } }
整个server类的代码为
package org.example; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class Server { static int port = 8888; ServerSocket serverSocket; List<Socket> list = new ArrayList<>(); BufferedReader in; BufferedWriter out; public Server(){ try { serverSocket = new ServerSocket(port); System.out.println("open server in " + port); } catch (IOException e){ e.printStackTrace(); } while(true){ try { Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress().toString() + ":" + socket.getPort()); list.add(socket); ClientThread clientThread = new ClientThread(socket); clientThread.setSocketList(list); clientThread.start(); } catch (IOException e) { e.printStackTrace(); } } } }
ClientThread类
在ClientThread中,我们要完成信息的处理,即收发信息。首先,我们需要定义一些东西
LEDDao ledDao = new LEDDao(); Socket socket; BufferedReader in; BufferedWriter out; List<Socket> list;
在ClientThread的构造函数中,我们需要接收一个Socker对象作为参数,然后初始化输入输出流
ClientThread(Socket socket) throws IOException { this.socket = socket; in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); out.write("hello world\r\n"); out.flush(); }
然后设置线程的socket列表属性
void setSocketList(List<Socket> list){ this.list = list; }
然后重写run方法,需要通过while循环无限循环,保持线程运行,从输入流读取数据然后打印消息到控制台,判断接收到的消息是否包含“info:”字符串(info的作用是区分该命令是写入数据库的指令还是其他功能指令),如果包含该字符串,我们需要删除他,然后按照“,”对字符串分割,将信息添加到数据库当中去。如果不包含该字符串,则遍历列表,将接收到的信息写入输入流,进行LED的操控。
// 重写Thread类的run方法,定义线程的行为。此方法将在线程启动时自动执行。 @Override public void run(){ while(true){ // 无限循环,保持线程持续运行 try { String msg = in.readLine(); // 从输入流中读取一行数据,并赋值给msg变量 System.out.println(msg); // 打印接收到的消息到控制台 // 判断接收到的消息是否包含"Info:"字符串 if (msg.contains("Info:")) { // 如果包含,则删除"Info:"字符串 msg = msg.replace("Info:", ""); // 将消息按照逗号进行分割,并创建一个LED对象 String[] msgArray = msg.split(","); LED led = new LED(msgArray[0], msgArray[1], msgArray[2]); ledDao.add(led); // 将LED对象添加到ledDao中(这里假设ledDao是一个全局变量) } else { // 如果消息不包含"Info:"字符串,则将消息广播给其他客户端 for (Socket socket : list){ // 遍历线程的socket列表 if (socket == this.socket){ // 如果当前socket与列表中的某个socket相同,则跳过此次循环 continue; } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 为每个不同的socket创建一个新的输出流 out.write(msg + "\r\n"); // 将接收到的消息写入输出流,并添加一个换行符,然后刷新输出流以确保消息被发送出去 } } } catch (IOException e) { // 如果在读写过程中发生IO异常,则抛出RuntimeException异常并传入异常信息e throw new RuntimeException(e); } } // while循环结束 } // run方法结束
所以,这个ClientThread类的内容为:
package org.example; import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.IllegalFormatCodePointException; import java.util.List; public class ClientThread extends Thread{ LEDDao ledDao = new LEDDao(); Socket socket; BufferedReader in; BufferedWriter out; List<Socket> list; ClientThread(Socket socket) throws IOException { this.socket = socket; in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); out.write("hello world\r\n"); out.flush(); } void setSocketList(List<Socket> list){ this.list = list; } @Override public void run(){ while(true){ try { String msg = in.readLine(); System.out.println(msg); //判断是否包含Info: if (msg.contains("Info:")) { //删除Info: msg = msg.replace("Info:", ""); //截取 String[] msgArray = msg.split(","); LED led = new LED(msgArray[0], msgArray[1], msgArray[2]); ledDao.add(led); } else { for (Socket socket : list){ if (socket == this.socket){ continue; } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); out.write(msg + "\r\n"); out.flush(); } } } catch (IOException e) { throw new RuntimeException(e); } } } }
LED类
LED类的作用主要为定义一些需要录入数据库的属性内容,然后定义其get与set函数,然后将返回一串字符
package org.example; import java.util.Objects; public class LED { private int id; private boolean state; private String time; private String user; public LED(String state, String time, String user) { this.state = Objects.equals(state, "true"); this.time = time; this.user = user; } public LED(int id, boolean state, String time, String user) { this.id = id; this.state = state; this.time = time; this.user = user; } @Override public String toString() { return "LED{" + "id=" + id + ", state=" + state + ", time='" + time + '\'' + ", user='" + user + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } }
LEDDao类
LEDDao类则是为了处理数据库语句,其中涉及到数据库的增删查改
package org.example; public class LEDDao { boolean add(LED led) { String sql = "insert into led(state, time, user) values(?, ?, ?)"; String[] parameters = {String.valueOf(led.isState()), led.getTime(), led.getUser()}; return MySqlHelper.executeUpdate(sql, parameters); } boolean delete(LED led) { String sql = "delete from led where id = ?"; String[] parameters = {String.valueOf(led.getId())}; return MySqlHelper.executeUpdate(sql, parameters); } boolean update(LED led) { String sql = "update led set state = ?, time = ?, user = ? where id = ?"; String[] parameters = {String.valueOf(led.isState()), led.getTime(), led.getUser(), String.valueOf(led.getId())}; return MySqlHelper.executeUpdate(sql, parameters); } LED query(int id) { String sql = "select * from led where id = ?"; String[] parameters = {String.valueOf(id)}; LED led = null; Object[] objects = (Object[]) MySqlHelper.executeQuery(sql, parameters).get(0); if (objects != null) { led = new LED((int) objects[0], (boolean) objects[1], (String) objects[2], (String) objects[3]); } return led; } }
标签:led,String,IDEA,socket,new,public,out From: https://www.cnblogs.com/hcrzhi/p/17962604