Android学之客户端服务端Socket简单通信

来源:互联网 发布:数据魔方在哪里看 编辑:程序博客网 时间:2024/06/03 20:31

服务器端Socket直接在服务器Java控制台上运行,只要Java环境配置没有错误就行。

服务器端:

AndroidService类,开启一个Socket服务,指定端口为30000

public class AndroidService {    public static void main(String[] args) throws IOException {        ServerSocket service = new ServerSocket(30000);        while(true){            //等待客户端连接            Socket socket = service.accept();            new Thread(new AndroidRunable(socket)).start();        }    }}
AndroidRunable类,向客户端返回hello world

public class AndroidRunable implements Runnable {    Socket socket = null;    public AndroidRunable(Socket socket){        this.socket = socket;    }    @Override    public void run() {        //向android客户端输出hello world        String line = null;        InputStream inputStream;        OutputStream outputStream;        String str = "hello world!";        //向客户端发送消息        try{            outputStream = socket.getOutputStream();            inputStream = socket.getInputStream();            BufferedReader bff = new BufferedReader(new InputStreamReader(inputStream));            outputStream.write(str.getBytes("gbk"));            outputStream.flush();            //半关闭socket            socket.shutdownOutput();            //获取客户端的信息            while ((line = bff.readLine()) != null) {                System.out.print(line);            }            //关闭输入输出流            outputStream.close();            bff.close();            inputStream.close();            socket.close();        }catch (IOException e){            e.printStackTrace();        }    }}
安卓客户端:

首先加入联网许可

布局XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.konghao.androidsocket.MainActivity">    <TextView        android:id="@+id/text"        android:layout_marginLeft="20dp"        android:textSize="18dp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <LinearLayout        android:layout_alignParentBottom="true"        android:layout_width="match_parent"        android:layout_height="wrap_content">        <EditText            android:id="@+id/edit"            android:layout_weight="0.7"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:hint="给服务器发送信息"/>        <Button            android:id="@+id/send"            android:layout_weight="0.3"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_marginBottom="10dp"            android:text="发送"/>    </LinearLayout></RelativeLayout>
MainActivity

public class MainActivity extends Activity implements View.OnClickListener{    Socket socket = null;    String buffer = "";    private TextView text;    private EditText edit;    private Button send;    private String getedit;    private static final int UPDATE = 1;    Handler handler = new Handler(){        @Override        public void handleMessage(Message msg){            super.handleMessage(msg);            switch (msg.what){                case UPDATE:{                    Bundle bundle = msg.getData();                    text.append("server:"+bundle.getString("msg")+"\n");                }                    break;            }        }    };    class MyThread extends Thread{        public String text1;        public MyThread(String str){            text1 = str;        }        @Override        public void run(){            Message msg = new Message();            msg.what = UPDATE;            Bundle bundle = new Bundle();            bundle.clear();            try{                //连接服务器 并设置连接超时为5秒                socket = new Socket();                socket.connect(new InetSocketAddress("112.74.92.125",30000),5000);                //获取输入输出流                OutputStream ou = socket.getOutputStream();                BufferedReader bff = new BufferedReader(new InputStreamReader(                        socket.getInputStream()));                //读取发来服务器信息                String line = null;                buffer = "";                while ((line = bff.readLine()) != null) {                    buffer = line + buffer;                }                Log.d("孔昊",buffer.toString());                //向服务器发送信息                ou.write("android".getBytes("gbk"));                ou.flush();                bundle.putString("msg", buffer.toString());                msg.setData(bundle);                //发送消息 修改UI线程中的组件                handler.sendMessage(msg);                //关闭各种输入输出流                bff.close();                ou.close();                socket.close();            }catch (SocketTimeoutException e){                //连接超时 在UI界面显示消息                bundle.putString("msg", "服务器连接失败!请检查网络是否打开");                msg.setData(bundle);                //发送消息 修改UI线程中的组件                handler.sendMessage(msg);            }catch (IOException e){                e.printStackTrace();            }        }    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text = (TextView) findViewById(R.id.text);        edit = (EditText) findViewById(R.id.edit);        send = (Button) findViewById(R.id.send);        send.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch(view.getId()){            case R.id.send:{                getedit = edit.getText().toString();                text.append("client:"+getedit+"\n");                new MyThread(getedit).start();            }                break;        }    }}






阅读全文
0 0
原创粉丝点击