1
votes

I am doing an android socket programming. However, I get some send and receive problem. Please help.

Server: I run it using Visual Studio C++ Client: Android client

When I am using below

Socket socket = new Socket(dstName,dstPort);        
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(method);

It can send the message to the server. However, When I am using OutputStreamWriter, it cannot send to server.

Question 1: What is the difference between OutputStreamWriter and PrintWriter??

On the other hand, I am going to make a UDP socket. So, I am using DatagramSocket

DatagramSocket udpSocket = new DatagramSocket();
byte[]outBuf = "this is a text".getBytes();
DatagramPacket dataPacket = new DatagramPacket(outBuf, outBuf.length);
dataPacket.setAddress(InetAddress.getByName(dstName));
dataPacket.setPort(dstPort);
dataPacket.setLength(outBuf.length);
udpSocket.send(dataPacket);

It also cannot reach to the server.

Question 2: Why DatagramSocket and OutputStreamWriter cannot send the data to my local server?? Only printWriter with Socket can reach it?

Many thanks

3

3 Answers

0
votes

It seems like your server is expecting a new line for each message. PrintWriter.println() sends one (as the name implies). With OutputStreamWriter you have to send the newline explicitly.

0
votes

Make connection through this class; it will return socket.

public class ChatApplication extends Application {

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}
0
votes

Outputstream is stream of bytes where as Writer is a stream of characters. Using Writer we can control the encoding style.

PrintWriter wrtr = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));