其他分享
首页 > 其他分享> > 使用socket实现即时通讯

使用socket实现即时通讯

作者:互联网

服务端和客户端分为两个不同的项目
服务端项目代码

package com.tszr;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ServerReceiveThread implements Runnable {

    private Socket socket;

    private static Logger log = LoggerFactory.getLogger(ServerReceiveThread.class);

    public ServerReceiveThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //输入流接收数据
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //输出流发送数据
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            while (true) {
                JSONObject jsonObject = (JSONObject) ois.readObject();
                System.out.println(jsonObject.toJSONString());
                String message = jsonObject.getString("msg");
                if ("close".equals(message)) {
                    oos.writeUTF("close");
                    oos.flush();
                    break;
                } else {
                    oos.writeUTF("接收数据成功" + message);
                    oos.flush();
                }
            }
            log.info("服务端关闭客户端[{}]", socket.getRemoteSocketAddress());
            oos.close();
            ois.close();
            socket.close();
        } catch (Exception e) {
            log.info("接收数据异常socket关闭");
            e.printStackTrace();
        } finally {
            log.info("数据异常数据要怎么保留");
        }
    }
}
package com.tszr;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class ServerSocketConfig {

    private static Logger log = LoggerFactory.getLogger(ServerSocketConfig.class);

    public static ServerSocket serverSocket = null;

    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    @Bean
    public void socketCreate() {
        try {
            serverSocket = new ServerSocket(5030);
            log.info("socket服务端开启");
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("接收到客户端socket" + socket.getRemoteSocketAddress());
                threadpool.execute(new ServerReceiveThread(socket));
            }
        } catch (IOException e) {
            log.info("socket服务启动异常");
            e.printStackTrace();
        }
    }
}
package com.tszr;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SocketServerApp {
    public static void main(String[] args){
        SpringApplication.run(SocketServerApp.class,args);
    }
}
server:
  port: 5030
客户端代码

package com.tszr;

import com.alibaba.fastjson.JSONObject;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientHeartThread implements Runnable{

    private String host;
    private int port;

    public ClientHeartThread(String host, int port){
        this.host = host;
        this.port = port;
    }

    @Override
    public void run() {
        try {
            Socket socket = new Socket(host,port);
            System.out.println("心跳socket链接成功");
            //输出流写数据
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //输入流读数据
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            int i =0;
            while (true){
                Thread.sleep(3000);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type","heart");
                jsonObject.put("msg","第"+i+"次心跳");
                System.out.println("发送心跳socket");
                oos.writeObject(jsonObject);
                oos.flush();
                i++;
                String message = ois.readUTF();
                System.out.println("接收到服务端响应"+message);
                if("close".equals(message)){
                    break;
                }
            }
            ois.close();
            oos.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package com.tszr;

import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientPrintThread implements Runnable{

    private String host;
    private int port;

    public ClientPrintThread(String host,int port){
        this.host = host;
        this.port = port;
    }
    @Override
    public void run() {
        try {
            Socket socket = new Socket(host,port);
            System.out.println("业务socket链接成功");
           // 输出流写数据
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            Scanner scanner = new Scanner(System.in);
            //输入流读数据
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            while (true){
                String str = scanner.nextLine();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type","body");
                jsonObject.put("msg",str);
                oos.writeObject(jsonObject);
                oos.flush();
                //写的部分
                String message = ois.readUTF();
                System.out.println("接收到服务端响应"+message);
                if("close".equals(message)){
                    break;
                }
            }
            ois.close();
            oos.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.tszr;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App {
    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);
    private static String host = "127.0.0.1";
    private static int port = 5030;

    public static void main(String[] args){
        executorService.execute(new ClientHeartThread(host,port));
        executorService.execute(new ClientPrintThread(host,port));
    }
}

 

标签:java,socket,实现,即时通讯,port,new,import,public
来源: https://www.cnblogs.com/tszr/p/16181927.html