Construi um server em socket assim:
classe principal
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORTA);
System.out.println(“INICIADO”);
while(true){
Socket socket = serverSocket.accept();
new ServicoThread(socket).start();
}
}
classe serviço extendendo thread
private final Socket socket;
public ServicoThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
ExecutaServico ClasseExecutora = new ExecutaServico(in);
ClasseExecutora.enviar(out);
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
classe executora
public ExecutaServico(DataInputStream in) {
String nomeServico = “”;
try {
this.servico = DataInputStream.readUTF(in).toString().trim();
if(servico.trim().equals(“02”)){
nomeServico = “INSERE”;
this.nome = DataInputStream.readUTF(in);
this.posicao = DataInputStream.readUTF(in);
} catch (IOException ex) {
Logger.getLogger(ExecutaServico.class.getName()).log(Level.SEVERE, null, ex);
}
public void enviar(DataOutputStream out) throws IOException{
if (this.servico.equals("02")) { //INSERE
int i = cadastrarPosicao();
if(i > 0){
out.writeUTF("1");
} else {
out.writeUTF("0");
}
}
public synchronized int cadastrarPosicao(){
int i = 0;
try {
cs = bd.conectar().prepareCall("{call RSDB_0005_SPI(?,?)}");
cs.setString(1, nome);
cs.setString(2, posicao);
i = cs.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (cs != null){
cs.close();
cs = null;
}
} catch (SQLException c){ }
bd.desconectar();
}
return i;
}
Até aqui fiz certo? Tem alguma coisa que precise ser implementada a mais? Nunca usei socket por isso a insegurança.
Agora estou tendo problemas com DeadLocks, alguem poderia me ajudar, preciso “aparecer” com esta solução até segunda-feira, por favor…
Luciano