繁体   English   中英

C# 服务器,Android Java 客户端 - 连接问题

[英]C# Server, Android Java Client - Connection issues

I'm currently working on a University project in which we send data from an Arduino to a C# server (works already), which then uses TCP to pass on the info to an Android app with a java client running on it. 不幸的是,后者还没有完全发挥作用。 我已经可以在客户端和服务器之间建立连接,并从虚拟手机(Android Studio)向服务器发送消息,但反过来不行。 我对 java 非常陌生,因此非常感谢您的每一点帮助!

我附上了下面的代码:

C# 服务器:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;

public class SocketServer
{
    public static void Main()
    {
        Parallel.Invoke
        (
            () => Arduino(),
            () => Android()
        );
    }


    public static void Arduino()
    {
        //Removed since unnecessary for question
    }

    public static void Android()
    {
        StreamReader streamReader_App;
        NetworkStream networkStream_App;

        TcpListener tcpListener_App = new TcpListener(1010);
        tcpListener_App.Start();

        Console.WriteLine("The Server has started on port 1010");

        int msg;

        while (true)
        {
            Socket serverSocket_App = tcpListener_App.AcceptSocket();

            try
            {
                Console.WriteLine("App-Client connected");
                networkStream_App = new NetworkStream(serverSocket_App);

                streamReader_App = new StreamReader(networkStream_App);
                msg = 0;

                while (msg == 0)
                {
                    var line_App = streamReader_App.ReadLine();
                    if (line_App == "CoordRequest")
                    {
                        System.Threading.Thread.Sleep(3000);
                        Console.WriteLine(line_App);
                        //Send coordinates to App
                        string message = "Test";
                        byte[] bytes = Encoding.ASCII.GetBytes(message+"\r\n");
                        networkStream_App.Write(bytes, 0, bytes.Length);
                        bytes = new byte[1024];
                        msg = 1;
                    }
                }

                networkStream_App.Close();
                serverSocket_App.Close();
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

Java 客户端(在Android上)启动客户端并接收消息:MainActivity.java

package com.example.tcpclient;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    EditText e1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1 = (EditText)findViewById(R.id.editText);

        Thread myThread = new Thread(new MyServerThread());
        myThread.start();
    }

    class MyServerThread implements Runnable
    {
        Socket s;
        ServerSocket ss;
        InputStreamReader isr;
        BufferedReader bufferedReader;
        Handler h = new Handler();

        String message;

        @Override
        public void run()
        {
            try
            {
                ss = new ServerSocket(1010);
                while(true)
                {
                    s = ss.accept();
                    isr = new InputStreamReader(s.getInputStream());
                    bufferedReader = new BufferedReader(isr);
                    message = bufferedReader.readLine();

                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }catch(IOException e)
            {
            e.printStackTrace();
            }
        }
    }

    public void send(View v)
    {
        MessageSend messageSender = new MessageSend();
        messageSender.execute(e1.getText().toString());
    }
}

Java 客户端(在Android上)发送消息:MessageSend.java

package com.example.tcpclient;

import android.os.AsyncTask;

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

public class MessageSend extends AsyncTask<String,Void,Void>
{
    Socket s;
    DataOutputStream dos;
    PrintWriter pw;

    @Override
    protected Void doInBackground(String... voids) {

        String message = voids[0];
        try
        {
            s = new Socket("192.168.1.10",1010);
            pw = new PrintWriter(s.getOutputStream());
            pw.write(message);
            pw.flush();
            pw.close();
            s.close();

        }catch(IOException e)
    {
        e.printStackTrace();
    }



        return null;
    }
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tcpclient">
    <uses-permission android:name = "android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

您正在使用 Socket 监听 Tcp 客户端
Socket serverSocket_App = tcpListener_App.AcceptSocket();

请按照以下代码更正您的代码

public static void Android()
{
    NetworkStream networkStream_App;

    // Buffer reader
    byte[] bytes = new byte[1024];
    string data = null;

    int port = 1010;

    //Replace IP with the IP of your C# server
    IPAddress ipAddress = IPAddress.Parse("192.168.43.153");

    TcpListener tcpListener_App = new TcpListener(ipAddress, port);
    tcpListener_App.Start();

    Console.WriteLine("The Server has started on port 1010");

    int msg;

    while (true)
    {
        TcpClient client = tcpListener_App.AcceptTcpClient();

        try
        {
            Console.WriteLine("App-Client connected");
            networkStream_App = client.GetStream();

            while ((msg = networkStream_App.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Get data 
                data = Encoding.ASCII.GetString(bytes, 0, msg);
                if (data.Equals("CoordRequest"))
                {
                    System.Threading.Thread.Sleep(3000);
                    Console.WriteLine(data);
                    //Send coordinates to App
                    string message = "Test";
                    byte[] msgToClient = Encoding.ASCII.GetBytes(message + "\r\n");
                    networkStream_App.Write(msgToClient, 0, msgToClient.Length);
                    Console.WriteLine(message);
                }
            }

            networkStream_App.Close();
            tcpListener_App.Stop();
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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