小弧光的博客

公众号:小弧光黑板报

导航

android socket编程

Client :


package org.lxh.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

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

public class MyClientDemo extends Activity {
    private Button send = null;
    private TextView info = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);
        this.send = (Button) super.findViewById(R.id.send);
        this.info = (TextView) super.findViewById(R.id.info);
        this.send.setOnClickListener(new SendOnClickListener());
    }

    private class SendOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            try {
                Socket client = new Socket("192.168.1.114", 8888);
                PrintStream out = new PrintStream(client.getOutputStream());
                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
                out.println("北京魔乐科技软件学院") ;    // 向服务器端发送数据
                MyClientDemo.this.info.setText(buf.readLine()) ;
                out.close() ;
                buf.close() ;
                client.close() ;
            } catch (Exception e) {
                e.printStackTrace() ;
            }
        }

    }
}

Server :


package org.lxh.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8888);
        Socket client = server.accept(); // 接收客户端请求
        PrintStream out = new PrintStream(client.getOutputStream());
        BufferedReader buf = new BufferedReader(new InputStreamReader(
                client.getInputStream()));
        StringBuffer info = new StringBuffer() ;
        info.append("Android : ") ;
        info.append(buf.readLine()) ;
        out.print(info) ;
        out.close() ;
        buf.close() ;
        client.close() ;
        server.close() ;
    }

}

posted on 2013-06-28 16:50  小弧光  阅读(311)  评论(0编辑  收藏  举报