1 回答
TA贡献1875条经验 获得超5个赞
我通过创建一个可运行的线程解决了这个问题。这将使您的服务器保持活动状态,直到您关闭它以及客户端是否断开连接。尝试这个...
public static void main(String[] args) throws IOException, ISOException {
final ServerSocket serverSocket = null;
Socket socket = null;
new Thread(new Runnable(){
@Override
public void run(){
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server siap menerima koneksi pada port ["+PORT+"]");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
InputStreamReader inStreamReader = new InputStreamReader(socket.getInputStream());
PrintWriter sendMsg = new PrintWriter(socket.getOutputStream());
int data;
StringBuffer sb = new StringBuffer();
int counter = 0;
int lengthOfMsg = 4;
while((data = inStreamReader.read()) != 0) {
counter++;
sb.append((char) data);
if (counter == 4) lengthOfMsg += Integer.valueOf(sb.toString());
if (lengthOfMsg == sb.toString().length()) {
System.out.println("Rec. Msg ["+sb.toString()+"] len ["+sb.toString().length()+"]");
processingMsg(sb.toString(), sendMsg);
}
}
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
}
}
}).start();
}
如果这不适合你,你可以参考我的代码。
String ip = "";
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
ip = socket.getLocalAddress().getHostAddress();
}
catch (Exception e){
e.printStackTrace();
}
txt.append("SERVER STARTED\n");
txt.append("Server IP Address: " + ip + "\n\n");
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Server.this.txt.append("Waiting for file...\n");
final ServerSocket server = new ServerSocket(8998);
server.close();
server = new ServerSocket(8998);
Server.this.socket = server.accept();
final Date date = new Date();
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
final String curDate = dateFormat.format(date);
final BufferedReader br = new BufferedReader(new InputStreamReader(Server.this.socket.getInputStream()));
final PrintWriter pw = new PrintWriter(new FileWriter(Server."C:\\Test\\File-" + curDate + ".csv"));
try {
String line;
for (line = br.readLine(); line != null; line = br.readLine()) {
wordsarray = line.split("\t");
pw.println(line);
}
pw.flush();
pw.close();
}
catch (IOException ex) {
System.out.printf("Can't write to file. ", ex);
}
finally {
if (Server.this.socket != null) {
br.close();
pw.close();
server.close();
Server.this.txt.append("\nAutomatically Saved to " + "C:\\PDT\\DataScan\\PurchaseOrder-" + curDate + ".csv" + "\n\n");
System.out.printf("Success! ");
}
}
}
}
catch (Exception e) {
System.out.printf("Something's Wrong! \n" + e);
JOptionPane.showMessageDialog(Server.this, e + "\n\nThe server needs to restart.", "Something's Wrong!", 1);
dispose();
main(null);
}
}
}).start();
它一直保持活动状态,直到我关闭服务器或应用程序,并且还处理多个连接/请求。
添加回答
举报