利用Socket与服务器端交互的简单Android范例代码

3y8nn的头像 3y8nn 9 2015-01-15 17:20 0

 基本信息

× 1   

浏览数: 5499

分享时间: 4 年 前

2

在Android中可以直接利用java中的Socket与ServerSocket构建socket通信。 代码的运行环境: pc端:普通pc,作为服务器,在5648端口进行监听。

代码运行一切正常,客户端发送的文字将在服务器端接收并显示,服务器每接收到客户端的一行文字,就会返回一个从0开始递增的整数,此整数将在客户端显示出来。 pc端代码:
package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Test implements Runnable{

    /**
     * @param args
     */

    int max=10;      //最大开启线程数
    int i=0;         //回复数字
    int temp;
    ServerSocket serverSocket;
    Socket socket[];

    public Test(){

        try {
            serverSocket=new ServerSocket(5648);    //在5648端口进行侦听
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("can't initate ServerSocket!");
            return;
        }

        socket=new Socket[max];

        System.out.println("waiting for connect");
        try {
            while((socket[i]=serverSocket.accept())!=null){
                temp=i;
                i++;
                new Thread(this).start();           //每侦听到一个客户端的连接,就会开启一个工作线程

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Test();

    }

    @Override
    public void run() {
        Socket sk=socket[temp];
        System.out.println("accept:"+sk.getInetAddress().getHostAddress());
        InputStream is=null;
        OutputStream os=null;
        BufferedReader br=null;
        PrintWriter pw=null;
        try {
            is=sk.getInputStream();
            os=sk.getOutputStream();
            br=new BufferedReader(new InputStreamReader(is));
            pw=new PrintWriter(os);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                sk.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            return;
        }
        String str;
        try {
            int m=0;
            while((str=br.readLine())!=null){
                System.out.println(str);
                pw.println(m);
                pw.flush();
                m++;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

android设备客户端代码: MainActivity.java;代码:
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.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,Runnable{

    private Button button;
    private EditText editText;
    private Socket socket;
    private PrintWriter pw;
    private BufferedReader br;
    private Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler=new Handler();
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(this);
        editText=(EditText)findViewById(R.id.edittext);
        try {
            socket=new Socket("tobacco5648.xicp.net",5648);        //连接到tobacco5648.xicp.net的5648端口
} catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("socket","unknown host");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("socket","io execption");
        }
        if(socket==null){
            Log.e("socket","null");
        }
        else
            try {
            pw=new PrintWriter(socket.getOutputStream());
            br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            if(pw!=null&&br!=null){
                new Thread(this).start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void onClick(View view) {
        if(view==button){
            String str;
            str=editText.getText().toString();
            pw.println(str);
            pw.flush();
        }

    }

    public void run() {

        try {
            String str;
            while((str=br.readLine())!=null){
                final String s=str;
                handler.post(new Runnable(){

                    public void run() {
                        Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();

                    }});

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}


12 3 4 5 6 [下一页]

  • ossaa的头像 ossaa 2018-06-23 19:15 代码数:0

    Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

    קידום אתרים

  • gererik的头像 gererik 2018-07-01 22:30 代码数:0

    Merely  a smiling  visitant here to share the love (:, btw  outstanding  style.Merely  a smiling  visitant here to share the love (:, btw  outstan ding  style.  breast surgery London

  • digital112的头像 digital112 2018-05-16 23:06 代码数:0

    Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information.

    water slide rentals Cincinnati

  • ossaa的头像 ossaa 2018-11-13 15:25 代码数:0

    Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.

    jual cctv

  • ys3301的头像 ys3301 2015-06-11 18:52 代码数:0
    楼主您好:
        
        请问下PC端代码运行在eclipse中行吗,或者运行在什么环境下。
         客户端的代码我自己弄一下,在手机上打不开APP。
        如果楼主您方便的话能把项目代码发给我,  qq  330136零28。
       

          非常感谢!!!
           非常感谢!!!
          非常感谢!!!
  • ossaa的头像 ossaa 2018-11-17 21:52 代码数:0

    I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information.

    Agentur für Arbeit

  • cixexey的头像 cixexey 2018-11-18 19:17 代码数:0

    I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit. travel information

  • lukeman的头像 lukeman 2019-01-16 00:23 代码数:0

    Currently, Kappa Sigma isn't recognized as a fraternity at Central because theuniversity lacks a formal Greek system. ... “The battle that we are currently fighting is to get a formal Greek system started on campus, paving the way for other fraternities and sororities to colonize and charter,” Stephens said <a href="http://centralwashingtonuniversity.org">http://centralwashingtonuniversity.org</a>

  • lukeman的头像 lukeman 2019-01-16 00:24 代码数:0
  • jhoneila的头像 jhoneila 2019-01-16 20:29 代码数:0

    This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information...check over here

您的评论: