0

我想将数据从 android 发送到 C#。C# 是服务器。Android 是客户端我将我的计算机连接到移动热点,但我收到此错误:

无法连接到 192.168.1.15(端口 4444):连接失败:ENETUNREACH(网络无法访问

这是java代码:

public class MainActivity extends Activity {

    //TextView tv=(TextView) findViewById(R.id.textView2);
    EditText edittext1;

    private TCPClient mTcpClient;

    private Button btnIP;
    private TextView txt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt1 = (TextView) findViewById(R.id.textView1);

        final EditText editText = (EditText)findViewById(R.id.edit_message);
        edittext1=(EditText) findViewById(R.id.editText1);
        btnIP=(Button) findViewById(R.id.button1);
        Button bt2=(Button) findViewById(R.id.button2);
        bt2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                txt1.setText(TCPClient.log) ;
            }
        });
                Button send = (Button)findViewById(R.id.send_button);
                // connect to the server
                new connectTask().execute("");
                btnIP.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        TCPClient.SERVERIP=edittext1.getText().toString();
                        new connectTask().execute("");
                    }
                });
                send.setOnClickListener(new OnClickListener()
                {

                @Override
                public void onClick(View view) {
                String message = editText.getText().toString();
                //sends the message to the server 
                if (mTcpClient != null) 
                {
                    mTcpClient.sendMessage(message); 
                }
                editText.setText(""); 
                }
                }); 
                }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public class connectTask extends AsyncTask<String,String,TCPClient> 
    {
        @Override 
        protected TCPClient doInBackground(String... message) 
        {
            mTcpClient = new TCPClient(new OnMessageReceived()
            { 
                @Override public void messageReceived(String message)
                {
                    publishProgress(message);
                    }
                }); 
            Looper.prepare();
            mTcpClient.run(); 
            return null;
            } 
        @Override 
        protected void onProgressUpdate(String... values) 
        {
            super.onProgressUpdate(values);
        } 


        }  



    public static class TCPClient 
    {
        private String serverMessage;
        public static String SERVERIP = "192.168.1.15";
        public static final int SERVERPORT = 4444; 
        private OnMessageReceived mMessageListener = null;
        public static String log="";
        private boolean mRun = false; 
        PrintWriter out;
        BufferedReader in; 
        DataOutputStream dataOutputStream = null;
        //OutputStream os; 
        public TCPClient(OnMessageReceived listener) 
        {
            mMessageListener = listener;

        } 
        public void sendMessage(String message)
        { 
            if (out != null && !out.checkError()) 
        { 
                /* String toSend = "a"; byte[] toSendBytes = toSend.getBytes(); 
        int toSendLen = toSendBytes.length; byte[] toSendLenBytes = new byte[4];
         toSendLenBytes[0] = (byte)(toSendLen & 0xff); toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff); toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff); toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff); try { os.write(toSendLenBytes); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { os.write(toSendBytes);
    } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */
            out.print(message);
            out.flush();
            } 
        } 
        public void stopClient()
        {
            mRun = false;
        }
        public void run()
        { 
//          TextView tv=(TextView) findViewById(R.id.textView2);
            //tv.setText(tv.getText()+"\n"+ "run");
            mRun = true; 

            try
            {
                InetAddress serverAddr = InetAddress.getByName(SERVERIP); 
        Log.e("TCP Client", "C: Connecting...");
        log="C: Connecting...";
        //Toast.makeText(MainActivity.this, "Connecting", Toast.LENGTH_SHORT).show();
        //tv.setText(tv.getText()+"\n"+ "Connecting");
        //tv.setText(tv.getText()+"\n"+ "Connecting...");
        Socket socket = new Socket(serverAddr, SERVERPORT); 

        /// //os = socket.getOutputStream(); 
        if(socket.isBound())
        { 

            Log.i("SOCKET", "Socket: Connected"); 
            log="Connected";
            //tv.setText(tv.getText()+"\n"+ "Connected");
            //Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
            //tv.setText(tv.getText()+"\n"+ "Connected");
        } 
        else{
            Log.e("SOCKET", "Socket: Not Connected");
            log="Not Connected";
        //  tv.setText(tv.getText()+"\n"+ "not Connected");
            //Toast.makeText(MainActivity.this, "not Connected", Toast.LENGTH_SHORT).show();
            //tv.setText(tv.getText()+"\n"+ " Not Connected");
        } try { 
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            //out.println(new char[]{'h','e'});
            //out.flush();
    /* dataOutputStream = new DataOutputStream(socket.getOutputStream()); byte[] bytes = new byte[] {1};
     *  dataOutputStream.write(bytes, 0, bytes.length); */
            Log.e("TCP Client", "C: Sent.");
            log=" Sent";
            Log.e("TCP Client", "C: Done."); 
            log=" Done";
            if(out.checkError())
            { 
                Log.e("PrintWriter", "CheckError");
            }
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (mRun) 
            {
                serverMessage = in.readLine();
            if (serverMessage != null && mMessageListener != null) 
            {
                mMessageListener.messageReceived(serverMessage);
                }
            serverMessage = null; 
            }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
            } catch (Exception e) { Log.e("TCP", "S: Error", e); } 
        finally { socket.close(); }
    } 
        catch (Exception e) { Log.e("TCP", "C: Error", e);
        log=e.getMessage();
        //tv.setText(tv.getText()+"\n"+ e.getMessage());
    }
        }


    }


}

C#代码:

class Program
    {
        static private IPAddress getLocalIPAddress()
        {
            IPHostEntry host;
            //string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                   // localIP = ip.ToString();
                    return ip;
                    //break;
                }
            }
           // return localIP;
            return null;
        }
        static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[2048];

            IPEndPoint ipep = new IPEndPoint(getLocalIPAddress(), 4444);

            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
        ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(10);
            Console.WriteLine("Waiting for a client...");

            Socket client = newsock.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port{1}", clientep.Address, clientep.Port);
            string welcome = "Welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);
            while (true)
            {

                data = new byte[1024];
                recv = client.Receive(data);
                if (recv == 0)
                    break;
                Console.WriteLine(Encoding.ASCII.GetString(data, 0,
                recv));
                client.Send(data, recv, SocketFlags.None);
            }
            Console.WriteLine("Disconnected from{0}", clientep.Address);
            client.Close();
            newsock.Close();
        }
    }
4

0 回答 0