Mein Clienttyp ist Android und die Sprache ist Java.Sende JSON String an Server
Diese Klasse stellt eine Verbindung zum Server her und ruft den Ausgabestream zum verbundenen Server ab.
class ConnectToServer extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
try {
socket = new Socket(ip,port);
output = new DataOutputStream(socket.getOutputStream());
Log.d(TAG, "Connected To Server!");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class SendToServer extends AsyncTask<Void, Void, Void>
{
//Our Json object
JSONObject obj;// = new JSONObject();
//this class is called when the login button is pressed, it sends the username and password as arguments
public SendToServer(String username, String password)
{
//instantiate the new object
obj = new JSONObject();
try {
//create the first field Type
obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request
obj.put("username", username); //our server will get username
obj.put("password",password); //our server will get password
} catch (JSONException e) {
e.printStackTrace(); //if we get problems let the developer know
}
}
@Override
protected Void doInBackground(Void... params)
{
String jsonText = obj.toString(); //convert our json object into a string
byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array
try {
output.writeInt(b.length); // write length of the message
output.write(b); // write the message
output.flush(); //flush - empties the pipe
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
Der Zweck dieses Codes ist der Server die Benutzer-Anmeldeinformationen zu senden.
In diesem C# Server
private void serverClient()
{
while(true)
{
int len = ns.ReadByte(); //read how much data
if (len == 0) //if this == 0 this means client has quit the program
break; //break out of loop and remove client from array list
if (len > 0) //we have a message
{
//read mess
byte[] message = new byte[len]; //create byte array
ns.Read(message, 0, message.Length); //read into the message byte array
string text = Encoding.ASCII.GetString(message, 0, len);
string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got.
Console.WriteLine(text1);
}
}
removeClients();
}
So wird das Android-Client der Anmeldeinformationen senden, aber wenn die SendToServer
Klasse aufgerufen wird, trennt der Client vom Server.
Wie kann ich eine JSON-Zeichenfolge an meinen C# -Server senden, damit sie die Zeichenfolge lesen und in ein Objekt serialisieren kann, abhängig von den Feldern.
Ihr Java-Code, soweit ich das beurteilen kann, schreibt nur auf ein JSON-Objekt - nichts mit Vernetzung zu tun. – Rob
@Rob Ich habe Code hinzugefügt, der zeigt, dass der Client eine Verbindung zum Server herstellt und den Ausgabestream empfängt. Die Schreibmethode des Ausgabestroms wird dann in der Klasse "SendToServer" verwendet. – Moynul