springboot搭建非阻塞式tcp服务器和客户端

工作区间新建项目

D:\workspace\eshore-build\eshore-build-tcpnio

新建Application.java

D:\workspace\eshore-build\eshore-build-tcpnio\src\main\java\com\eshore\build\tcpnio\Application.java

其内容为

package com.eshore.build.tcpnio;

import java.text.SimpleDateFormat;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.FixedSubscriberChannel;
import org.springframework.integration.ip.tcp.TcpInboundGateway;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpSendingMessageHandler;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author jiangyl
 *
 */
@SpringBootApplication
@EnableScheduling
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Autowired
	private Gateway gateway;

	@Scheduled(fixedDelay = 1000L)
	public void sendMessageJob() {
		String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
		String msg = "{\"currentTime\":\"" + currentTime + "\"}";
		System.out.println("客户端发送消息" + msg);
		gateway.sendMessage(msg);
	}

	// server
	@Bean
	public AbstractServerConnectionFactory serverConnectionFactory() {
		return new TcpNioServerConnectionFactory(5678);
	}

	@Bean
	public MessageChannel requestChannel() {
		return new DirectChannel();
	}

	@Bean
	public TcpInboundGateway tcpInboundGateway() {
		TcpInboundGateway tcpInboundGateway = new TcpInboundGateway();
		tcpInboundGateway.setConnectionFactory(serverConnectionFactory());
		tcpInboundGateway.setRequestChannel(requestChannel());
		return tcpInboundGateway;
	}

	@Transformer(inputChannel = "requestChannel", outputChannel = "requestChannel2")
	public String serverConvert(byte[] bytes) {
		return new String(bytes);
	}

	@ServiceActivator(inputChannel = "requestChannel2")
	public String handleRequest(String msg) throws Exception {
		System.out.println("服务端处理请求消息=" + msg);// server handle
		ObjectMapper objectMapper = new ObjectMapper();
		Map map = objectMapper.readValue(msg, Map.class);
		map.put("result", "is processed");
		return objectMapper.writeValueAsString(map);
	}

	// client
	@Bean
	public AbstractClientConnectionFactory clientConnectionFactory() {
		return new TcpNioClientConnectionFactory("localhost", 5678);
	}

	@Component
	@MessagingGateway(defaultRequestChannel = "sendMessageChannel")
	public interface Gateway {
		void sendMessage(String message);
	}

	@Bean
	@ServiceActivator(inputChannel = "sendMessageChannel")
	public TcpSendingMessageHandler tcpSendingMessageHandler() {
		TcpSendingMessageHandler tcpSendingMessageHandler = new TcpSendingMessageHandler();
		tcpSendingMessageHandler.setConnectionFactory(clientConnectionFactory());
		return tcpSendingMessageHandler;
	}

	@Bean
	public TcpReceivingChannelAdapter tcpReceivingChannelAdapter() {
		TcpReceivingChannelAdapter tcpReceivingChannelAdapter = new TcpReceivingChannelAdapter();
		tcpReceivingChannelAdapter.setConnectionFactory(clientConnectionFactory());
		tcpReceivingChannelAdapter.setOutputChannelName("outputChannel");
		return tcpReceivingChannelAdapter;
	}

	@Transformer(inputChannel = "outputChannel", outputChannel = "outputChannel2")
	public String clientConvert(byte[] bytes) {
		return new String(bytes);
	}

	/*@Bean
	public MessageChannel outputChannel2() {
		return new FixedSubscriberChannel(msg -> {
			System.out.println("客户端处理响应消息=" + msg.getPayload());// client handle
		});
	}

	@Bean
	@ServiceActivator(inputChannel = "outputChannel2")
	public MessageHandler handleResponse() {
		return msg -> {
			System.out.println("客户端处理响应消息=" + msg.getPayload());// client handle
		};
	}*/

	@ServiceActivator(inputChannel = "outputChannel2")
	public String handleResponse(String msg) throws Exception {
		System.out.println("客户端处理响应消息=" + msg);// client handle
		return null;
	}

}



新建配置文件pom.xml

D:\workspace\eshore-build\eshore-build-tcpnio\pom.xml

其内容为

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.eshore.build</groupId>
    <artifactId>eshore-build-tcpnio</artifactId>
    <version>1.0.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-ip</artifactId>
        </dependency> 
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

执行

命令行切换到D:\workspace\eshore-build\eshore-build-tcpnio,执行命令

mvn spring-boot:run

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Qt是一个跨平台的应用程序开发框架,它可以用来开发各种类型的应用程序,包括TCP服务器客户端。 在Qt中,可以使用Qt网络模块来实现TCP服务器客户端的功能。要同时运行TCP服务器客户端,可以在同一个应用程序中创建两个Qt网络对象,分别用于实现服务器客户端的功能。 首先,我们需要创建一个QTcpServer对象来实现TCP服务器的功能。通过调用QTcpServer的listen()函数来监听指定的IP地址和端口号,等待客户端的连接请求。当有新的客户端连接时,QTcpServer会自动发出newConnection()信号,我们可以通过连接这个信号的槽函数来处理新客户端的连接。 然后,我们需要创建一个QTcpSocket对象来实现TCP客户端的功能。通过调用QTcpSocket的connectToHost()函数来连接到服务器的IP地址和端口号。连接成功后,我们可以发送和接收数据。 在应用程序中,可以创建一个主窗口,同时创建一个QTcpServer对象和一个QTcpSocket对象。在主窗口中,可以增加一些用户界面元素,例如按钮和文本框,用于操作服务器客户端。当点击按钮时,可以通过QTcpServer和QTcpSocket对象来实现相应的功能,例如启动服务器、连接到服务器、发送数据等。 需要注意的是,在同一个应用程序中同时运行TCP服务器客户端可能需要一些线程管理的技术,以保证服务器客户端之间的通信不会阻塞主线程的运行。可以使用Qt的多线程技术来实现这一点,例如将服务器客户端的功能代码放在不同的线程中运行。 总而言之,通过使用Qt的网络模块,可以很方便地实现TCP服务器客户端的功能,并在同一个应用程序中同时运行它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值