gpt4 book ai didi

java - 添加一个线程,每次只处理1个socket

转载 作者:行者123 更新时间:2023-11-30 04:12:56 29 4
gpt4 key购买 nike

我如何在该代码中添加一个线程以每次仅允许 1 个连接...以及当它完成时 .close();再次打开还要等待另一个吗?我尝试了很多其他的东西,比如 WHILE、if 和其他变量,但未能阻止 .accept();当连接打开时;/,我不知道如何使其成为一个线程

import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Array;
import java.net.*;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Provider {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
String ocupado = "0";
ObjectInputStream in;
String caminhodoarquivo;
Provider(){}
void run()
{
try{
providerSocket = new ServerSocket(2004, 1);
System.out.println("---------------Aguardando por certidões----------------");
connection = providerSocket.accept();
out = new ObjectOutputStream(this.connection.getOutputStream());
out.flush();
sendMessage(ocupado);
in = new ObjectInputStream(connection.getInputStream());

System.out.println("Certidão de: " + connection.getInetAddress().getHostName());
String ocupado = "1";


try{
caminhodoarquivo = (String)in.readObject();
System.out.println("Certidão: " + caminhodoarquivo);

JTextField paginainicial = new JTextField();
JTextField paginafinal = new JTextField();
Object[] message = {
"Número da Primeira Folha: ", paginainicial,
"Número Última Folha: ", paginafinal,
};

int option = JOptionPane.showConfirmDialog(null, message, "Dados da Certidão", JOptionPane.OK_CANCEL_OPTION);
ocupado = "1";
if (option == JOptionPane.OK_OPTION) {

String primeirafolha = paginainicial.getText();
String ultimafolha = paginafinal.getText();
metodos metodosBD = new metodos();
metodosBD.atualizafolha(primeirafolha, ultimafolha, caminhodoarquivo);

System.out.println("Dados inseridos.");
Desktop.getDesktop().print(new File(caminhodoarquivo));
ocupado = "0";


} else {
System.out.println("Certidão Cancelada.");

}


}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
out.close();
in.close();
providerSocket.close();
}



}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}

void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}

}

Edit for the answer of user2511414

1)服务器运行正常,完美接收第一个连接,并在我关闭确认对话框时完成它,我可以完美打开另一个连接= OK

2) 当我连接 client1 时,保持确认对话框打开,并尝试连接第二个客户端,我在 CLIENT2 中收到此错误:

java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Sour
ce)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at certidoesOrganizado.PrimeiroPDF$Requester.run(PrimeiroPDF.java:151)
at certidoesOrganizado.PrimeiroPDF.enviacaminho(PrimeiroPDF.java:132)
at certidoesOrganizado.PrimeiroPDF.geracertidao(PrimeiroPDF.java:466)
at certidoesOrganizado.PrimeiroPDF.pegadados(PrimeiroPDF.java:302)
at certidoesOrganizado.gui$6.actionPerformed(gui.java:204)

在服务器中我收到了这个:

java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Unknown Source)
at Provider.run(Provider.java:21)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-4" java.lang.NullPointerException
at Provider.run(Provider.java:59)
at java.lang.Thread.run(Unknown Source)

并且Client2没有收到“服务器正忙”消息

3)虽然client1的ConfirmDialog仍然打开,并且在Client2失败后我尝试CLIENT3,它连接成功并且我以2个Joption.ShowConfirmDialog打开结束...:(

一切都重新开始,我在客户端中使用它来进行连接:

在调用连接的方法中:

Requester client = new Requester();

client.run();

类(class)请求者:

}
class Requester{
Socket requestSock

et;
ObjectOutputStream out;
ObjectInputStream in;
String message;

Requester(){}
void run()



{




try{

requestSocket = new Socket("localhost", 2004);



System.out.println("Tentando Conexão");
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
System.out.println("out.flush");
in = new ObjectInputStream(requestSocket.getInputStream());

try {
message = (String)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}







do{
message = "oi";
sendMessage(arquivonomecompleto);
}while(message.equals("bye"));

}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}


}

void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
//System.out.println("client>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}




}

最佳答案

我看到你的代码是单线程的,没有其他线程的迹象,一切都由主线程运行,其次我对某些部分有点困惑,首先你在得到输出后立即刷新输出,我的意思是你没有发送任何东西但冲洗它!

out = new ObjectOutputStream(this.connection.getOutputStream());
out.flush();

那么您如何看待您的应用程序并行运行?!

而关于在另一个线程(并且单个)中运行连接过程,这并不是一件很难的工作,首先实现Runnable接口(interface),并让run方法来处理连接处理。

public class Provider implements Runnable  {
...
public void run(){//manages the connection but ONE at a time.
while(true){
server.run();
}
}
public static void main(String[] arg){
Provider server = new Provider();
new Thread(this).start();//start the connection processing with another thread.
}
...
}

你也会有一个简单的thread tutorial here 。有一个很好的并行程序伙计:)

更新:并在第一个正在进行时拒绝第二个(带有一些消息),所以这也不是一项艰巨的工作,但第一件事是使过程并行,为此,我将 main 方法放入(剪切)到另一个类中,并让 Provider 类处理请求,同时保留 ServerSocket(port) OEPN。

import java.awt.Desktop;
import java.io.*;
import java.lang.reflect.Array;
import java.net.*;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Provider implements Runnable {
// ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
String ocupado = "0";
ObjectInputStream in;
String caminhodoarquivo;
Provider(Socket s){this.connection=s;}
@Override
public void run()
{
try{
out = new ObjectOutputStream(this.connection.getOutputStream());
//out.flush();
sendMessage(ocupado);
in = new ObjectInputStream(connection.getInputStream());
System.out.println("Certidão de: " + connection.getInetAddress().getHostName());
String ocupado = "1";
try{
caminhodoarquivo = (String)in.readObject();
System.out.println("Certidão: " + caminhodoarquivo);
JTextField paginainicial = new JTextField();
JTextField paginafinal = new JTextField();
Object[] message = {
"Número da Primeira Folha: ", paginainicial,
"Número Última Folha: ", paginafinal,
};
int option = JOptionPane.showConfirmDialog(null, message, "Dados da Certidão", JOptionPane.OK_CANCEL_OPTION);
ocupado = "1";
if (option == JOptionPane.OK_OPTION) {
String primeirafolha = paginainicial.getText();
String ultimafolha = paginafinal.getText();
metodos metodosBD = new metodos();
metodosBD.atualizafolha(primeirafolha, ultimafolha, caminhodoarquivo);
System.out.println("Dados inseridos.");
Desktop.getDesktop().print(new File(caminhodoarquivo));
ocupado = "0";
}else {System.out.println("Certidão Cancelada.");}
}catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
out.close();
in.close();
connection.close();
}
}
catch(IOException ioException){ioException.printStackTrace();}
finally{
Server.setFree();//Tells server the system is ready for new connection.
//4: Closing connection
try{
in.close();
out.close();
connection.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}

void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
// public static void main(String args[])
// {
// Provider server = new Provider();
// while(true){
// server.run();
// }
// }

}

注意:当服务器繁忙时,此响应“Error -> Server is busy”作为字符串,因此客户端需要检查服务器是否响应单个字符串“Error -> Server is busy”,这意味着服务器没有响应任何内容否则。

class Server implements Runnable{
private final String serverBusyMessage="Error -> Server is busy";
private ServerSocket ss;
private static volatile boolean busy=false;
public static void setFree(){busy=false;}
public void run(){
while(true){
try{Socket s=ss.accept();
if(busy){//if there is one connection processing.
ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
out.writeObject(serverBusyMessage);
out.flush();
s.close();continue;
}
System.out.println("---------------Aguardando por certidões----------------");
new Thread(new Provider(s)).start();
busy=true;
}catch(Exception e){}
}
}
private Server(){try{ss=new ServerSocket(2004);}catch(Exception ex){}}
public static void main(String[] arg){
Server server = new Server();
new Thread(server).start();
}
}

关于java - 添加一个线程,每次只处理1个socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19188148/

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