简体   繁体   中英

Sending Java Client String to C# Server

I am quite new to networking, and have so far managed to get my Android app (client) to connect with my Unity C# server, however I am getting a bit stuck with the Java sending the String and the server decoding it.

The C# client will read input, but when I Log the client message, it is black. So my best guess is that the problem lies with the Java string encoding or the decoding.

Let me know if anyone can spot where I am going wrong, or if anyone has better suggestions on how to handle the writers and the readers.

Many thanks in advance!

The java Client SendMsg Thread

 import android.os.AsyncTask;
import android.util.Log;

import java.io.DataOutputStream;
import java.net.Socket;

public class SendMsgToServer extends AsyncTask<Socket, Void, Void> {


    @Override
    protected Void doInBackground(Socket... sockets) {

        Socket client = sockets[0];

        //Check Connection is established
        if (client.isConnected()){
            try {
                String msgToServer = "Pleasure doing business";
                DataOutputStream data = new DataOutputStream(client.getOutputStream());
                data.writeUTF(msgToServer);

                // Source: http://stackoverflow.com/questions/11154367/socket-java-client-c-sharp-server
//                PrintWriter outputMsg = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//                outputMsg.write("Message to the Server.");
                Log.d("Server", data.toString());

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.d("Server", "Server Connection is not established");
        }




        return null;
    }
}

The C# Server

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class clientTcp : MonoBehaviour {

    static bool socketReady = false;
    static TcpListener server = null;
    static NetworkStream networkStream;
    static StreamWriter writer; 
    static StreamReader reader;
    static Byte[] bytes = new Byte[256];
    static NetworkStream stream;
    static TcpClient client;
    String Host = "localhost";
    Int32 port = 13000;


    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
    public void setupSocketServer() {
            //Create thread to accept the connection ; else Unity crashes
        Thread acceptClient = new Thread(new ThreadStart(SocketClient));
        acceptClient.Start();


    }
    //msg is from the textfield
    public void writeSocket(string msg) {

        if (socketReady == false) {
            return;
        }
        String data = "hi";
        byte[] msgToClient = System.Text.Encoding.ASCII.GetBytes(data);
        stream.Write(msgToClient, 100, msg.Length);

    }

    public void readSocket() {

        Thread readClient = new Thread (new ThreadStart (ReadClient));
        readClient.Start ();

    }

    static void ReadClient() {
        Debug.Log ("ReadClient Thread started");

        // http://stackoverflow.com/questions/29265430/socket-communication-between-java-and-c-sharp-application

        int length = networkStream.ReadByte ();
        byte[] buffer = new byte[length];


        int size = networkStream.ReadByte ();
        byte[] buff = new byte[size];
        using (var memoryStream = new MemoryStream(buff,false)) {
            using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) {
                var message = streamReader.ReadLine();
                buff = Encoding.UTF8.GetBytes(message);
                networkStream.Read(buffer, 0 ,buffer.Length);
                Debug.Log (message);
                networkStream.Flush();
            }

        }
    }


    //Thread to set up the Unity Server and await connection request from the Android App.
    static void SocketClient() {

        Int32 port = 13000;
        IPAddress serverAddr = IPAddress.Parse("192.168.1.15");
        //Establish Server
        server = new TcpListener(serverAddr, port);
        server.Start();

        //Await connection
        while (true) {
            client = server.AcceptTcpClient ();
            Debug.Log("Client Connected");
            socketReady = true;
            networkStream = client.GetStream();
            writer = new StreamWriter(networkStream);
            reader = new StreamReader(networkStream);

            String data= null;

            //Create a stream object for reading and writing
            stream = client.GetStream();
            Debug.Log("client.getStream");
//          int i;
//          while((i = stream.Read(bytes,0,bytes.Length)) != 0 ) {
//              data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//              Debug.Log(data);
            }
        }
    }

事实证明我错过了这行代码:

string mess = System.Text.Encoding.UTF8.GetString(buff);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM