2020-09-16 Java Socket 使用

本文介绍了一个基于Java的Socket通信案例,包括服务端与客户端的实现细节。服务端通过构造函数注入多个业务服务对象,如WaterMonitorCodeService、IndexRecordsService等,用于处理客户端请求。客户端连接至指定IP及端口,发送与接收信息。

Java Socket 使用 以及对象注入

服务端

public class Server {

    private static WaterMonitorCodeServiceImpl waterMonService;
    private static IndexRecordsServiceImpl indexRecordsService;
    private static GiveAlarmServiceImpl giveAlarmService;
    private static DeviceServiceImpl deviceService;
    private static IndexValueServiceImpl indexValueService;
    private static RedisUtil redis;

    public Server(WaterMonitorCodeServiceImpl waterMonService,
                  IndexRecordsServiceImpl indexRecordsService,
                  GiveAlarmServiceImpl giveAlarmService,
                  DeviceServiceImpl deviceService,
                  IndexValueServiceImpl indexValueService,
                  RedisUtil redis){
        this.waterMonService=waterMonService;
        this.indexRecordsService=indexRecordsService;
        this.giveAlarmService=giveAlarmService;
        this.deviceService=deviceService;
        this.indexValueService=indexValueService;
        this.redis=redis;
    }

    //public static void main(String[] args) throws IOException {
    public void run() throws IOException {
        Socket socket=null;
        List<String> userCount=new ArrayList<>();
        int count=0;
        try {
            ServerSocket serverSocket=new ServerSocket(8484);
            while(true){
                socket =serverSocket.accept();
                ServerThread serverThread=new ServerThread(socket,waterMonService,indexRecordsService
                        ,giveAlarmService,deviceService,indexValueService,redis);
                serverThread.start();
                InetAddress addr = socket.getInetAddress();
                if (userCount.size()==0) {
                    userCount.add(addr.getHostAddress());
                    System.out.println("connection from:"+addr.getHostName()+"--IP:"+addr.getHostAddress());
                }else {
                    if (userCount.contains(addr.getHostAddress())){
                        count--;
                    }else {
                        userCount.add(addr.getHostAddress());
                    }
                }
                count++;
                System.out.println("客户端的数量为:"+count+"--IP:"+addr.getHostAddress());
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(socket!=null){
                socket.close();
            }
        }

    }

}

服务端线程类

package cn.nkhb.socket;

import cn.nkhb.entity.*;
import cn.nkhb.service.Impl.*;
import cn.nkhb.util.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.nkhb.util.ContantUtil.*;
import static cn.nkhb.util.DateTimeUtil.getDate;

public class ServerThread extends Thread {

    private Socket socket = null;
    private BufferedReader br = null;
    private PrintWriter pw = null;
    private List<String> infoList = new ArrayList<>();

    private WaterMonitorCodeServiceImpl waterMonitorCodeService;
    private IndexRecordsServiceImpl indexRecordsService;
    private GiveAlarmServiceImpl giveAlarmService;
    private DeviceServiceImpl deviceService;
    private IndexValueServiceImpl indexValueService;
    private IndexStatusUtil indexStatusUtil;
    private RedisUtil redis;


    public ServerThread(Socket socket,
                        WaterMonitorCodeServiceImpl waterMonitorCodeService,
                        IndexRecordsServiceImpl indexRecordsService,
                        GiveAlarmServiceImpl giveAlarmService,
                        DeviceServiceImpl deviceService,
                        IndexValueServiceImpl indexValueService,
                        RedisUtil redis) {
        this.socket = socket;
        this.waterMonitorCodeService = waterMonitorCodeService;
        this.indexRecordsService = indexRecordsService;
        this.giveAlarmService = giveAlarmService;
        this.deviceService = deviceService;
        this.indexValueService = indexValueService;
        indexStatusUtil = new IndexStatusUtil(indexValueService);
        this.redis = redis;
    }

    private Map map;


    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            //获取输入流,并读取客户端信息
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            InetAddress addr = socket.getInetAddress();
            String info = "";
            while ((info = br.readLine()) != null) {
                System.out.println(info);
                 //此处是 把客户端的信息 存在本地对象 infoList中
                infoList.add(info);
            }

            socket.shutdownInput();   //关闭输入流
            pw = new PrintWriter(socket.getOutputStream());

               //此处 可以发送给客户端
                pw.write("");
            
            pw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
                if (br != null)
                    br.close();
                if (pw != null)
                    pw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

客户端

package cn.nkhb.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	public static void main(String[] args) throws IOException {
		Socket socket=null;
		PrintWriter pw=null;
		BufferedReader br=null;
		try {

				socket = new Socket("172.18.10.70", 8484);
				pw = new PrintWriter(socket.getOutputStream());
				//发送消息给 服务端
				pw.write("##\r\n");
				pw.flush();
				socket.shutdownOutput();

				br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				String info = null;
				//读取 服务端发送的消息
				while ((info = br.readLine()) != null) {
					System.out.println("服务器 say--" + info);
				}
				socket.shutdownInput();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(socket!=null){
				socket.close();
			}
			if(pw!=null){
				pw.close();
			}
			if(br!=null){
				br.close();
			}

		}
	}

}

在socket中,不能注入service对象。我这里是在创建服务端的时候,构造函数注入。

package cn.nkhb;

import cn.nkhb.entity.CodeDetail;
import cn.nkhb.entity.DataAnalye;
import cn.nkhb.entity.DataArea;
import cn.nkhb.entity.InfoData;
import cn.nkhb.service.Impl.*;
import cn.nkhb.util.RedisUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

import cn.nkhb.socket.Server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.nkhb.util.DateTimeUtil.getDate;

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@MapperScan("cn.nkhb.mapper")
@ComponentScan("cn.nkhb")
public class SocketApplication implements CommandLineRunner{

    @Autowired private WaterMonitorCodeServiceImpl waterMonitorCodeService;
    @Autowired private IndexRecordsServiceImpl indexRecordsService;
    @Autowired private GiveAlarmServiceImpl giveAlarmService;
    @Autowired private DeviceServiceImpl deviceService;
    @Autowired private IndexValueServiceImpl indexValueService;
    @Autowired private RedisUtil redis;



    public static void main(String[] args) {
        SpringApplication.run(SocketApplication.class, args);
        System.out.println("1111111111");
    }

    @SuppressWarnings("unchecked")
    @Override
    public void run(String... args) throws Exception {
        //注入对象
        Server server=new Server(
                waterMonitorCodeService,indexRecordsService,
                giveAlarmService,deviceService,indexValueService,
                redis);
        server.run();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值