今天也算是做了个实验吧
实验材料: 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,只用笔记本电脑就好的: