AotoIT3客户端代码:
#include
;; 启动TCP
TCPStartup();
;; 建立TCP连接
$address = "127.0.0.1" ;;通讯地址
$port=8888 ;;通讯端口
$ConnectedSocket = TCPConnect($address, $port)
If @error Then
MsgBox(4112, "error", "TCP连接错误: " & @error)
EndIf
;; 发送TCP字符串
$data = "hello,i am client.";
TCPSend($ConnectedSocket, $data);
If @error Then
MsgBox(4112, "error", "发送数据连接错误: " & @error)
Else
MsgBox(64, "提示", "发送数据完成! ")
EndIf
Java服务器端代码:
package com.what21;
import java.io.IOException;
import .InetSocketAddress;
import .ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NIOTcpServer {
private Selector selector;
public NIOTcpServer(int port) throws IOException {
// 打开服务器套接字通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 服务器配置为非阻塞
serverSocketChannel.configureBlocking(false);
// 检索与此通道关联的服务器套接字
ServerSocket serverSocket = serverSocketChannel.socket();
// 进行服务的绑定
serverSocket.bind(new InetSocketAddress(port));
// 通过open()方法找到Selector
selector = Selector.open();
// 注册到selector,等待连接
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server Start 8888.");
}
// 监听
private void listen() throws IOException {
while (true) {
// 选择一组键,并且相应的通道已经打开
selector.select();
// 返回此选择器的已选择键集。
Set selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
handleKey(selectionKey);
}
}
}
/**
* @param selectionKey
* @throws IOException
*/
private void handleKey(SelectionKey selectionKey) throws IOException {
// 接受请求
ServerSocketChannel server = null;
SocketChannel client = null;
int count = 0;
if (selectionKey.isAcceptable()) {
server = (ServerSocketChannel) selectionKey.channel();
client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
} else {
try{
client = (SocketChannel) selectionKey.channel();
ByteBuffer receivebuffer = ByteBuffer.allocate(4096);
count = client.read(receivebuffer);
if (count > 0) {
String receiveText = new String(receivebuffer.array(), 0, count);
System.out.println("接收数据: " + receiveText);
client.register(selector, SelectionKey.OP_CONNECT);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int port = 8888;
NIOTcpServer server = new NIOTcpServer(port);
server.listen();
}
}
如果觉得《autoit java_AutoIt3客户端和Java服务器端TCP通信》对你有帮助,请点赞、收藏,并留下你的观点哦!