gpt4 book ai didi

java - 多次连接到套接字

转载 作者:行者123 更新时间:2023-11-30 04:33:14 26 4
gpt4 key购买 nike

好的,当我第一次连接时一切正常。但是当我再次连接(不停止服务器程序)时,它显示“连接被拒绝:连接”。我认为这是因为我只接受一次连接,所以我使用 Swing Timer 每 10 毫秒触发一次操作事件,每次触发操作事件时,它都会将 clientSocket 设置为 serverSocket.accept() (clientSocket = serverSocket.accept( );) 所以这是代码:

package org.code;

import java.net.*;
import java.io.*;

public class MainClass {
public static void main(String[] args) {
new MainClass();
}


Socket server = null;
PrintWriter out = null;

public MainClass() {
try {
server = new Socket("192.168.0.104", 4444);
out = new PrintWriter(server.getOutputStream(), true);

out.println("start");

out.close();
server.close();
} catch(Exception ex) {ex.printStackTrace();}
}
}

还有:

package org.code;

import java.io.*;
import java.net.*;
import javax.swing.*;

public class MainClass {
public static void main(String[] args) {
new MainClass();
}

ServerSocket serverSocket = null;

Socket clientSocket = null;

BufferedReader in;

public MainClass() {
JFrame frame = new JFrame("Minecraft Server Manager v0.1 Server");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

try {
serverSocket = new ServerSocket(4444);

clientSocket = serverSocket.accept();

in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String inputLine;

while((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
if(inputLine.equals("start")) {
System.out.println("Good");
}
if(inputLine.equals("stop")) {
System.out.println("Bad");
}
}

clientSocket.close();
serverSocket.close();
} catch(Exception ex) {System.err.println("Error: " + ex.getMessage());}
}
}

最佳答案

您的代码在每次请求后都会关闭 ServerSocket(并且也会停止)。

这更有可能起作用。 (我没有测试它,但有了这个你就得到了场景)

// in your main 
serverSocket = new ServerSocket(4444);

try {
while (true) {
clientSocket = serverSocket.accept();

Thread t = new ClientSocketThread(clientSocket);
t.start();
}
} finally {
serverSocket.close();
}


class ClientSocketThread extends Thread {
final Socket clientSocket;

ClientSocketThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}

public void run() {
InputStream in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try
String inputLine;

while((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
if(inputLine.equals("start")) {
System.out.println("Good");
}
if(inputLine.equals("stop")) {
System.out.println("Bad");
}
}
} finally {
in.close()
clientSocket.close();
}
}
}

关于java - 多次连接到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114812/

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