当客户端连接到我的服务器时如何制作程序/执行某些操作以及如何使服务器返回客户端?

时间:2015-07-25 10:51:58

标签: java c# android

这是我在网络上的网络服务器工作代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;

namespace Youtube_Manager
{
    class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;

        public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");

            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");

            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);

            _responderMethod = method;
            _listener.Start();
        }

        public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("Webserver running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = _responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }
}

然后在form1构造函数中:

WebServer ws = new WebServer(SendResponse, "http://+:8098/");//"http://localhost:8080/test/");
ws.Run();

form1中的方法:

public static string SendResponse(HttpListenerRequest request)
        {
            return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
        }

在客户端java代码:

package com.test.webservertest;

import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;

import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

//import com.adilipman.webservertest.DebugServer;


public class MainActivity extends ActionBarActivity
{
    private static final int MY_DATA_CHECK_CODE = 0;
    public static MainActivity currentActivity;
    TextToSpeech mTts;
    private String targetURL;
    private String urlParameters;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setContentView(new SingleTouchEventView(this, null));

        currentActivity = this;

        initTTS();


    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings)
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Dispatch onStart() to all fragments.  Ensure any created loaders are
     * now started.
     */
    @Override
    protected void onStart()
    {
        super.onStart();

        TextToSpeechServer.main(null);
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    public void initTTS() {
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == MY_DATA_CHECK_CODE) {
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                mTts = new TextToSpeech(getApplicationContext(), new OnInitListener() {

                    @Override
                    public void onInit(int i) {

                        if(i == TextToSpeech.SUCCESS) {
                            int result = mTts.setLanguage(Locale.US);
                            if(result == TextToSpeech.LANG_AVAILABLE
                                    || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                                mTts.setPitch(1);
                                mTts.speak(textforthespeacch, TextToSpeech.QUEUE_FLUSH, null);
                            }
                        }
                    }
                });
            } else {
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    public static String textforthespeacch = "";
    public static void TextToSpeak(String text) {
        textforthespeacch = text;
    }

    public class SingleTouchEventView extends View {
        private Paint paint = new Paint();
        private Path path = new Path();
        private Path circlePath = new Path();

        public SingleTouchEventView(Context context, AttributeSet attrs) {
            super(context, attrs);

            paint.setAntiAlias(true);
            paint.setStrokeWidth(6f);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawPath(path, paint);
            canvas.drawPath(circlePath, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();

            float lastdownx = 0;
            float lastdowny = 0;

            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
                    lastdownx = eventX;
                    lastdowny = eventY;

                    Thread t = new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            byte[] response = Get(null);
                            if (response!=null)
                                Logger.getLogger("MainActivity(inside thread)").info(response.toString());


                        }
                    });
                    t.start();




                    return true;
                case MotionEvent.ACTION_MOVE:
                    path.lineTo(eventX, eventY);
                    break;
                case MotionEvent.ACTION_UP:
                    // nothing to do
                    circlePath.reset();

                    break;
                default:
                    return false;
            }

            // Schedules a repaint.
            invalidate();
            return true;
        }
    }

    private byte[] Get(String urlIn)
    {
        URL url = null;
        String urlStr="http://10.0.0.2:8098";
        if (urlIn!=null)
            urlStr=urlIn;

        try
        {
            url = new URL(urlStr);
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
            return null;
        }
        HttpURLConnection urlConnection = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            byte[] buf=new byte[10*1024];
            int szRead = in.read(buf);

            byte[] bufOut;

            if (szRead==10*1024)
            {
                throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
            }
            else
            {
                bufOut = Arrays.copyOf(buf, szRead);
            }


            return bufOut;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            if (urlConnection!=null)
                urlConnection.disconnect();
        }
    }



}

首先我在电脑上运行服务器。 然后我在Android上运行程序,当我在我的智能手机上触摸时客户端连接到PC上的服务器。

现在我想做的是两件事:

  1. 连接到pc服务器时做点什么。将设备连接到PC服务器后,请执行以下操作:
  2. MessageBox.Show("connected"); 2.连接后,如果使用标志或其他东西连接,则返回一个字符串给客户端。我在电脑上有一个名为SendData的方法,我用它将字符串发送到我的Android设备上的服务器:

    private void SendDataToServer()
            {
                // Create a request using a URL that can receive a post. 
                WebRequest request = WebRequest.Create("http://10.0.0.3:8080/?say=hello? im here ");
                // Set the Method property of the request to POST.
                request.Method = "POST";
                // Create POST data and convert it to a byte array.
                string postData = "This is a test that posts this string to a Web server.";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                Console.WriteLine(responseFromServer);
                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();
            }
    

    问题是,如果我想从我的电脑服务器向客户端返回一些内容,我是否需要使用此方法?

0 个答案:

没有答案