gpt4 book ai didi

Java socketserver如何测试?

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:18 25 4
gpt4 key购买 nike

我想通过java中的套接字连接接收文本文件,我设置了服务器端,但在继续客户端之前,我想知道我编写的代码是否有效,但我不知道如何测试它。

任何帮助将不胜感激..

编辑:我知道端口已打开并正在监听请求,我想要的是测试如果它收到任何内容会发生什么,它会从输入创建一个文件吗?我可以通过模拟来测试它(发送我不知道的文件或字节)吗?

public class Server {

private static int port = 8080;
private static int maxConnections = 100000;

// Listen for incoming connections and handle them
public static void startServer() {
int i = 0;

try {
ServerSocket listener = new ServerSocket(port);
Socket server;

System.out.println("Started server on port:" + port);

while ((i++ < maxConnections) || (maxConnections == 0)) {
RunServer connection;

server = listener.accept();
RunServer conn_c = new RunServer(server);
Thread t = new Thread(conn_c);
t.start();

System.out.println("Created new thread");
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

class RunServer implements Runnable {
private Socket server;

RunServer(Socket server) {
this.server = server;
}

public void run() {
int bytesRead;
int current = 0;
BufferedOutputStream bufferedOutputStream = null;
FileOutputStream fileOutputStream = null;
DataInputStream clientData = null;
File file = null;

try {
// creating connection.
System.out.println("connected.");

// receive file
byte[] byteArray = new byte[6022386];
System.out.println("Please wait downloading file");

// reading file from socket
InputStream inputStream = server.getInputStream();
file = new File("toread.txt");
clientData = new DataInputStream(inputStream);
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(byteArray, 0, byteArray.length);

current = bytesRead;
do {
bytesRead = inputStream.read(byteArray, current, (byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);

bufferedOutputStream.write(byteArray, 0, current);
bufferedOutputStream.flush();

ReaderHelper.readTextFile(file);

} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
if (bufferedOutputStream != null)
bufferedOutputStream.close();
if (clientData != null)
clientData.close();
if (server != null)
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

那么,您的套接字将在端口 8080 上运行,对吧?

您可以打开浏览器并输入:http://localhost:8080 。浏览器将创建一个连接和线路

server = listener.accept();

将“解锁”。如果你只是想测试套接字是否正在监听,那就可以了。读取该流,您将看到 HTTP 协议(protocol)的第一条消息。

关于Java socketserver如何测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com