Socket Java + C

6 respostas
brunobuild

Client em C e Server em JAVA.

Não estou conseguindo ler o que o Client© envia para o server(JAVA).

Eu vi um tópico que uma pessoa está falando para usar o InputStream mas também não estou conseguindo.
Existe alguma forma simples de fazer isso?

Estou precisando muito disso aqui no meu serviço.

Aguardo retorno

Obrigado, :-o

6 Respostas

thiago.correa

Eu tenho algo semelhante, para tal eu usei o apache mina! Simplificou o trabalho!

Mas posta aí o teu código para que o pessoal possa ver o que está errado!

brunobuild

segue o código

o código está bem simples

private BufferedReader	input;
	
	private PrintStream printStream;
	
	private Socket socket;

	/**
	 * @param clientSocket
	 */
	public ReceivingThread(Socket clientSocket)
	{
		super("ReceivingThread: " + clientSocket);

		try
		{
			//clientSocket.setSoTimeout(5000);
			
			//clientSocket.setReuseAddress(true);
			this.socket = clientSocket;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	} 
	
	/**
	 * @throws IOException
	 */
	private void getStream() throws IOException
	{
		this.printStream = new PrintStream(this.socket.getOutputStream());
		this.printStream.flush();
		
		this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
	}

	/** (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run()
	{
		this.execute();
	}
	
	/**
	 * 
	 */
	public synchronized void execute()
	{
		String message = "";
		
		try
		{
			this.getStream();
			
			while(!message.equals("CLIENT>>> fim") || message == null)
			{
				message = input.readLine();
				
				this.printStream.println("SERVER>>> " + message + ": Solicitação OK");
				
				if (message != null)
				{
					System.out.println("Mensagem Recebida: " + message);
				}
			}
			
			this.printStream.flush();	
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
brunobuild

Segue o código está bem simples.

você poderia me passar um exemplo como vc fez?

segue meu código

private BufferedReader	input;
	
	private PrintStream printStream;
	
	private Socket socket;

	/**
	 * @param clientSocket
	 */
	public ReceivingThread(Socket clientSocket)
	{
		super("ReceivingThread: " + clientSocket);

		try
		{
			//clientSocket.setSoTimeout(5000);
			
			//clientSocket.setReuseAddress(true);
			this.socket = clientSocket;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	} 
	
	/**
	 * @throws IOException
	 */
	private void getStream() throws IOException
	{
		this.printStream = new PrintStream(this.socket.getOutputStream());
		this.printStream.flush();
		
		this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
	}

	/** (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run()
	{
		this.execute();
	}
	
	/**
	 * 
	 */
	public synchronized void execute()
	{
		String message = "";
		
		try
		{
			this.getStream();
			
			while(!message.equals("CLIENT>>> fim") || message == null)
			{
				message = input.readLine();
				
				this.printStream.println("SERVER>>> " + message + ": Solicitação OK");
				
				if (message != null)
				{
					System.out.println("Mensagem Recebida: " + message);
				}
			}
			
			this.printStream.flush();	
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
brunobuild

Olá pessoal estou tentando usar o Apache Mina para trocar informações via socket.

Classe Main.

private static final int	PORT	= 9080;

	public static void main(String[] args) throws Exception
	{
		IoAcceptor acceptor = new SocketAcceptor();

		SocketAcceptorConfig cfg = new SocketAcceptorConfig();
		cfg.setReuseAddress(true);
		cfg.getFilterChain().addLast("logger", new LoggingFilter());
		cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

		acceptor.bind(new InetSocketAddress(PORT), new ReverseProtocolHandler(), cfg);
		System.out.println("Listening on port " + PORT);
	}

Classe ReverseProtocolHandler

public void exceptionCaught(IoSession session, Throwable cause)
	{
		cause.printStackTrace();
		session.close();
	}
	
	public void messageReceived(IoSession session, Object message)
	{
		String str = message.toString();
		StringBuffer buf = new StringBuffer(str.length());
		
		for (int i = str.length() - 1; i >= 0; i--)
		{
			buf.append(str.charAt(i));
		}

		session.write(buf.toString());
	}

Quando eu faço acesso de um client feito em java ele funciona bem mas quando eu faço o acesso de um client em C o server não consegue receber a mensagem.

Alguém poderia me ajudar?

:smiley:

brunobuild

:frowning:

brunobuild

Para deixar registrado

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
	public static void main(String[] args) throws IOException
	{
		try
		{
			System.out.println("Abrindo Socket...");
			ServerSocket waitSocket = new ServerSocket(9080);
			System.out.println("Socket Aberto");

			System.out.println("Aguardando Conexão...");
			// wait until a client attempts to connect
			Socket connection = waitSocket.accept();
			System.out.println("Conexão Aberta");

			// get an InputStream from the socket
			DataInputStream fromClient = new DataInputStream(connection.getInputStream());

			// get an OutputStream from the socket
			DataOutputStream toClient = new DataOutputStream(connection.getOutputStream());

			System.out.println("Recebendo Dados...");
			byte buffer[] = new byte[1000];
			fromClient.read(buffer);
			// fromClient.close();
			String conteudo = new String(buffer).trim();
			System.out.println("RECEBIDO: " + conteudo);
			System.out.println("Enviando Dados...");
			toClient.write(("Recebido: " + conteudo).getBytes());
			System.out.println("Enviado");
			connection.close();
			System.out.println("Socket Fechado");
		}
		catch (Exception e)
		{
			System.err.println("ERRO: " + e.getMessage());
		}
	}
Criado 26 de abril de 2010
Ultima resposta 27 de abr. de 2010
Respostas 6
Participantes 2