Fórum Dúvida Cliente/Servidor com Sockets #421054
04/08/2012
0
Estou tendo problemas pra programar um cliente/servidor com Sockets e Threads. Podem me ajudar no raciocínio?
Bem, tenho uma classe JANELA que faz a interface com o usuário. Nela eu tenho os botões Conectar, Download e Upload que chamam os métodos da minha classe CLIENTE.
Tá tudo funcionando direitinho, aparentemente. Porém, após me conectar, se eu clico em Download ele executa normal, mas se clico novamente nele ou em outro botão, me retorna um erro: java.net.SocketException: Socket closed; Ou seja, só estou conseguindo fazer uma requisição com o CLIENTE para o SERVIDOR.
Vejam minhas classes ..
CLIENTE ...
package FTPCliente_Servidor;
import java.awt.BorderLayout;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class Cliente extends Thread{
private Socket conexao;
public Cliente(){}
public Cliente(Socket s)//sobrecarga
{
this.conexao = s;
}
public void connect(String s) throws IOException {
try {
socketCliente = new Socket(s, 4321);
System.out.println(Conectado: +socketCliente.getInetAddress().getHostName());
out = socketCliente.getOutputStream();
in = socketCliente.getInputStream();
;
} catch (IOException e) {
System.out.println(e);
}
}
public void upload() {
try {
saida = new DataOutputStream(out);
saida.writeUTF(up);
File file = new File(source.JPG);
ObjectOutputStream os = new ObjectOutputStream(out);
FileInputStream fis = new FileInputStream(file);
byte[] cache = new byte[4096];
while (true) {
int len = fis.read(cache);
if (len == -1) {
break;
}
os.write(cache, 0, len);
}
os.flush();
os.close();
//socketCliente.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void download() {
try {
saida = new DataOutputStream(out);
saida.writeUTF(down);
byte[] cache = new byte[4096];
ObjectInputStream ois = new ObjectInputStream(in);
FileOutputStream fos = new FileOutputStream(download//up.JPG);
while (true) {
int len = ois.read(cache);
if (len == -1) {
break;
}
fos.write(cache, 0, len);
}
fos.flush();
fos.close();
} catch (Exception e) {
System.out.println(e);
}
}
static Socket socketCliente = null;
private OutputStream out;
private InputStream in;
private DataOutputStream saida;
}SERVIDOR ..
package FTPCliente_Servidor;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Servidor extends Thread {
private Socket conexao;
public Servidor(Socket s) {
this.conexao = s;
}
public static void main(String[] args) throws IOException {
ServerSocket servidor = (ServerSocket) null;
try {
servidor = new ServerSocket(4321, 300);
while (true) {
Socket conexao = servidor.accept();
Thread t = new Servidor(conexao);
t.start();
}
} catch (IOException e) {
}
}
public void run() {
try {
InputStream is = conexao.getInputStream();
DataInputStream dis = new DataInputStream(is);
String comando = dis.readUTF();
if (comando.trim().equals(up)) {
ClienteUpload();
} else if (comando.trim().equals(down)) {
ClienteDownload();
}
} catch (IOException e) {
System.out.println(e);
}
}
public void ClienteUpload() {
try {
InputStream is = conexao.getInputStream();
byte[] cache = new byte[4096];
ObjectInputStream ois = new ObjectInputStream(is);
FileOutputStream fos = new FileOutputStream(upload//up.JPG);
while (true) {
int len = ois.read(cache);
if (len == -1) {
break;
}
fos.write(cache, 0, len);
}
fos.flush();
fos.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void ClienteDownload() {
OutputStream out;
try {
out = conexao.getOutputStream();
File file = new File(source.JPG);
ObjectOutputStream os = new ObjectOutputStream(out);
FileInputStream fis = new FileInputStream(file);
byte[] cache = new byte[4096];
while (true) {
int len = fis.read(cache);
if (len == -1) {
break;
}
os.write(cache, 0, len);
}
os.flush();
os.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Gostaria muito de ajuda. Andei pesquisando e parece que devo criar uma Thread no cliente, mas não entendi o motivo ..
Estou aberta a sugestões e reclamações caso meu código não esteja logicamente correto .. mE Ajudem ..
Valeria Silva
Curtir tópico
+ 0Posts
06/08/2012
Davi Costa
att Davi
Gostei + 0
06/08/2012
Valeria Silva
Gostei + 0
06/08/2012
Davi Costa
e dá o feedback
att Davi
Gostei + 0
06/08/2012
Valeria Silva
Gostei + 0
06/08/2012
Davi Costa
De qualquer forma dá uma pesquisada mesmo.
Aki tenho um exemplo bem simple que fnciona assim:
package socket.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketSoma {
private Socket socket;
public SocketSoma(Socket socket) {
this.socket = socket;
}
public void soma() throws IOException {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
int n1 = in.read();
int n2 = in.read();
out.write(n1+n2);
in.close();
out.close();
socket.close();
}
}
package socket.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
public String soma(int n1, int n2) throws UnknownHostException, IOException {
Socket socket = new Socket(localhost, 4444);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(n1);
out.write(n2);
String toReturn = O resultado é: + in.read();
in.close();
out.close();
socket.close();
return toReturn;
}
}
package socket.client;
import java.awt.HeadlessException;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class Client {
public static void main(String args[]) throws HeadlessException, UnknownHostException, IOException{
int n1 = Integer.parseInt(JOptionPane.showInputDialog(Digite um nº:));
int n2 = Integer.parseInt(JOptionPane.showInputDialog(Digite um nº:));
JOptionPane.showMessageDialog(null, new ClientSocket().soma(n1,n2));
}
}
espero ter ajudado
att Davi
Gostei + 0
06/08/2012
Davi Costa
package socket.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4444);
System.out.println(server is running in 4444...);
while(true){
Socket socket = serverSocket.accept();
new SocketSoma(socket).soma();
}
}
}
att Davi
Gostei + 0
06/08/2012
Davi Costa
package socket.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4444);
System.out.println(server is running in 4444...);
while(true){
Socket socket = serverSocket.accept();
new SocketSoma(socket).soma();
}
}
}
att Davi
Gostei + 0
06/08/2012
Valeria Silva
Gostei + 0
06/08/2012
Davi Costa
att Davi
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)