android Socket与SocketServer


今天也算是做了个实验吧

实验材料: nexues7 ,笔记本,猎豹WiFi。

目的:实现nexue7 做客户端,连接笔记本上的服务器端。 源码来自:《疯狂android 讲义》


为啥要用猎豹WIFI呢?因为我的平板和电脑的IP不在同一网段,也没有公网IP的主机,为了使他们能局域网通信,猎豹WIFI为我省了无线路由。

还有一种方法,就是用电脑设置个无线网路,然后,nexues 7连接上。

步骤:

1.猎豹wifi 安装后,启动,nexues 7连接这个WiFi信号。

2.用cmd 可以看到,电脑的无线网卡的IP地址,


查看nexues 7的IP地址为 :192,.168.155.2


3.服务器端源码:

public class SimpleServer {
	
	public static void main(String[] args)throws IOException
	{
		//创建一个ServerSocket ,监听客户端socket的连接请求
		ServerSocket ss= new ServerSocket(8090,10,InetAddress.getByName ("192.168.155.1"));
		
		while(true)
		{
			Socket s=ss.accept();
			OutputStream os=s.getOutputStream();
			os.write("您好,您收到了来自服务器的新年祝福!\n".getBytes("utf-8"));
			os.close();
			s.close();
			
		}
		
		
	}

}


4.android 客户端源码:


public class SimpleClient extends Activity{

	
	 EditText show;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simpleclient);
		show=(EditText)findViewById(R.id.ed);
		
		new Thread()
		{
			@Override
			public void run()
			{
				try
				{
					Socket s=new Socket("192.168.155.1",8090);
					BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
					String line=br.readLine();
					show.setText("来自服务器的数据:"+line);
					br.close();
					s.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
			
		}.start();
		
		
		
	}//
	
	
	

}

OVER!

 还有一种新建无线局域网的功能,不用猎豹WIFI,只用笔记本电脑就好的: 







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值