socket 通信 入门3 android 客户端 C# 服务端

这是一个android端操控服务器的例子  就是发送简单指令到服务器  然后服务器响应什么的...

当然这里是未完成的  只是简单展示一下大致思路

首先连接建立起来后  服务端给客户端一条信息  告诉服务已经建立  然后客户端可以发送指令到服务端  

服务端在将处理的结果返回给客户端   没有使用到线程  因此必须是 客户端一句话 服务端一句话 这样交替进行

服务端

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace SocketOne
{
    class MyServer
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 8081;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
                s.Bind(ipe);//绑定8081端口
                s.Listen(0);//开始监听
                Console.WriteLine("Wait for connect");
                Socket temp = s.Accept();//为新建连接创建新的Socket。
                Console.WriteLine("Get a connect");
                string recvStr = "";
                string sendStr = "";

                //接收传送信息的时候都是发送的byte数组
                //首先向客户端发送信息                    
                sendStr = "Connection set up";
                //与java通信 后面加个\n  因为我的java用的是readline
                byte[] bs = Encoding.ASCII.GetBytes(sendStr + "\n");
                temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                int count = 1;
                
                MyResponse myresponse=new MyResponse();
                while (true)
                {
                    Console.WriteLine("a loop starts count="+ (count++) +"==================");
                    //接收信息
                    int bytes;
                    byte[] recvBytes = new byte[1024];
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                    recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);//
                    Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
                    

                    //经过我的处理后将信息返回给客户端
                    sendStr = myresponse.myresponse(recvStr);
                    Console.WriteLine("response is " + sendStr);
                    bs = Encoding.ASCII.GetBytes(sendStr + "\n");
                    temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                    Console.WriteLine("this loop end");
                    
                }
                //temp.Close();
                //s.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
    }
}

android客户端(仅仅是说明一下概念和原理  所以东西不多 全部放在了 activity里面)

package mypackage.hello;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Hello1Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initBtns();
        connectToServer();
    }

    Button btnAdd;
    Button btnDel;
    Button btnSearch;

    Socket socket;
    BufferedReader in;
    PrintWriter out;
    String recvStr = null;
    String sendStr = null;

    public void initBtns() {
        btnAdd = (Button) findViewById(R.id.buttonAdd);
        btnDel = (Button) findViewById(R.id.buttonDel);
        btnSearch = (Button) findViewById(R.id.buttonSearch);

        btnAdd.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    System.out.println("add clicked");
                    sendStr = "add,xxx,xxx,xxx";
                    out.println(sendStr);

                    recvStr = in.readLine();
                    System.out.println("response is " + recvStr);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        
        btnDel.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                try {
                    System.out.println("del clicked");
                    sendStr = "DEL,xxx";
                    out.println(sendStr);

                    recvStr = in.readLine();
                    System.out.println("response is " + recvStr);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        
        
        btnSearch.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                try {
                    System.out.println("search clicked");
                    sendStr = "search,xxx";
                    out.println(sendStr);

                    recvStr = in.readLine();
                    System.out.println("response is " + recvStr);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        });

    }

    public void connectToServer() {
        try {
            // 同时 为了使程序拥有网络权限 在manifest中要有 <uses-permission
            // android:name="android.permission.INTERNET" />
            // 否则提示 permission denied
            // 安卓模拟器将127.0.0.1默认为模拟器的本机地址 要得到计算机中真正的地址是 localhost/127.0.0.1 或者
            // 10.0.0.2
            socket = new Socket("10.0.2.2", 8081);
            System.out.println("after socket");
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader line = new BufferedReader(new InputStreamReader(
                    System.in));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

posted @ 2013-10-21 22:17  cart55free99  阅读(373)  评论(0编辑  收藏  举报