首页 > 其他分享 >socket(五)IDEA与socket

socket(五)IDEA与socket

时间:2024-03-24 12:33:48浏览次数:27  
标签:led String IDEA socket new public out

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

相关文章

  • ideaSSM 学员信息管理系统bootstrap开发mysql数据库web结构java编程计算机网页源码mav
    一、源码特点 idea开发SSM学员信息管理系统是一套完善的信息管理系统,结合SSM框架和bootstrap完成本系统,对理解JSPjava编程开发语言有帮助系统采用SSM框架(MVC模式开发),系统具有完整的源代码和数据库,系统主要采用B/S模式开发。前段主要技术bootstrap.cssjquery后端主要......
  • 全栈的自我修养 ———— webSocket中如何接受一个对象
    小编这里的场景是小程序,前后端如何搭配才能接收到一个对象?前端后端前端发送时候要变成json字符串functionsendOnLogin(online){constparams={type:'login',username:username,online:online}wx.sendSocketMessag......
  • 在idea中连接ubuntu 16中的docker
    在idea中连接ubuntu16中的docker前提ubuntu安装了docker1.安装docker插件,在file->settings中2.进入Build,Execution,Deployment->Docker通过加号添加这个时候其实不会图片中连接成功的标志,因为还没有配置docker服务,注意我虚拟机的ip为192.168.93.1313.配置dock......
  • WebSocket
    **WebSocket是一种在单个TCP连接上进行全双工通信的协议,它允许浏览器和服务器之间进行实时双向交互**。这项技术是HTML5的一部分,它在现代web开发中扮演着重要的角色。以下是关于WebSocket的一些详细信息:1.**全双工通信**:与传统的HTTP请求不同,WebSocket提供了一个持久的连接,通过......
  • idea很好用的mybatis插件
    mybatis_log_plugin此插件可以恢复sql日志为完整的可执行的sql语句、把sql日志里面的?替换为真正的值可以选择在idea里找到下载,也可以在外面下来jar包直接拖拽到idea里下载后在idea:点击后在下面就多了一个MyBatisLog:在运行后,一旦有执行mybat......
  • idea更新gitlab突然报错
    年前还用的好好的项目年后回来更新直接失败了,前后端都白搭,一样的报错:Updatefailed/opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_logger.rb:72:inwrite:Nospaceleftondevice@io_write-/var/log/gitlab/gitlab-shell/gitlab-shell.log(Errno::ENOSPC)f......
  • WebSocket的原理
    1.什么是websocketWebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的Websocket是一个持久化的协议2.websocket的原理websocket约定了一个通信的规范,通过一个握......
  • 网络通信Socket
    publicList<User>users=newList<User>();Socketsocket;//初始化服务器publicvoidInitSever(){  //创建一个Socket对象  socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);  //将把通信的地址和端口绑定到s......
  • 重新配置intelliJ-IDEA记录
    完善的intelliJ-IDEA辅导https://cdk8s.gitbook.io/github/about-this-tutorial 0224重新申请免费版本-等待-完成 需重启,记录当前参考网页首次运行向导main参考https://cdk8s.gitbook.io/github/first-run-wizard原位置https://github.com/judasn/IntelliJ-IDEA-Tutorial/......
  • IDEA项目路径初探
    IDEA项目路径初探:https://blog.csdn.net/qq_30591155/article/details/109046394?ops_request_misc=&request_id=&biz_id=102&utm_term=idea%20java%20%E7%89%88%E6%9C%AC%E7%9A%84%E9%A1%B9%E7%9B%AE%E7%9B%AE%E5%BD%95&utm_medium=distribute.pc_search_result.n......