安卓手机socket通信(服务器和客户端)
本文实例为大家分享了安卓手机socket通信代码,供大家参考,具体内容如下
1、socket通信首先要定义好服务端的ip地址和端口号;
(1).首先看服务端的代码:
packagecom.example.androidsockettest;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.ServerSocket;
importjava.net.Socket;
importandroid.net.wifi.WifiInfo;
importandroid.net.wifi.WifiManager;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.view.Menu;
importandroid.widget.TextView;
publicclassMainActivityextendsActivity{
publicstaticServerSocketserverSocket=null;
publicstaticTextViewmTextView,textView1;
privateStringIP="";
Stringbuffer="";
publicstaticHandlermHandler=newHandler(){
@Override
publicvoidhandleMessage(android.os.Messagemsg){
if(msg.what==0x11){
Bundlebundle=msg.getData();
mTextView.append("client"+bundle.getString("msg")+"\n");
}
};
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.textsss);
textView1=(TextView)findViewById(R.id.textView1);
IP=getlocalip();
textView1.setText("IPaddresss:"+IP);
newThread(){
publicvoidrun(){
Bundlebundle=newBundle();
bundle.clear();
OutputStreamoutput;
Stringstr="通信成功";
try{
serverSocket=newServerSocket(30000);
while(true){
Messagemsg=newMessage();
msg.what=0x11;
try{
Socketsocket=serverSocket.accept();
output=socket.getOutputStream();
output.write(str.getBytes("UTF-8"));
output.flush();
socket.shutdownOutput();
//mHandler.sendEmptyMessage(0);
BufferedReaderbff=newBufferedReader(newInputStreamReader(socket.getInputStream()));
Stringline=null;
buffer="";
while((line=bff.readLine())!=null){
buffer=line+buffer;
}
bundle.putString("msg",buffer.toString());
msg.setData(bundle);
mHandler.sendMessage(msg);
bff.close();
output.close();
socket.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}catch(IOExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}
};
}.start();
}
privateStringgetlocalip(){
WifiManagerwifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfowifiInfo=wifiManager.getConnectionInfo();
intipAddress=wifiInfo.getIpAddress();
//Log.d(Tag,"intip"+ipAddress);
if(ipAddress==0)returnnull;
return((ipAddress&0xff)+"."+(ipAddress>>8&0xff)+"."
+(ipAddress>>16&0xff)+"."+(ipAddress>>24&0xff));
}
}
(2).因为是手机做服务端,所以在开始操作的时候客户端是不知道ip和端口号的,但在服务端运行后就可以看到(亲:你可以自己测试)
2、客户端的代码
packagecom.example.andoroidclient;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.InetSocketAddress;
importjava.net.Socket;
importjava.net.SocketTimeoutException;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.app.Activity;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.TextView;
publicclassMainActivityextendsActivity{
Socketsocket=null;
Stringbuffer="";
TextViewtxt1;
Buttonsend;
EditTexted1;
Stringgeted1;
publicHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(msg.what==0x11){
Bundlebundle=msg.getData();
txt1.append("server:"+bundle.getString("msg")+"\n");
}
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1=(TextView)findViewById(R.id.txt1);
send=(Button)findViewById(R.id.send);
ed1=(EditText)findViewById(R.id.ed1);
newMyThread("建立连接").start();
send.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
geted1=ed1.getText().toString();
txt1.append("client:"+geted1+"\n");
//启动线程向服务器发送和接收信息
newMyThread(geted1).start();
}
});
}
classMyThreadextendsThread{
publicStringtxt1;
publicMyThread(Stringstr){
txt1=str;
}
@Override
publicvoidrun(){
//定义消息
Messagemsg=newMessage();
msg.what=0x11;
Bundlebundle=newBundle();
bundle.clear();
try{
//连接服务器并设置连接超时为5秒
socket=newSocket();
socket.connect(newInetSocketAddress("172.20.226.11",30000),1000);
//获取输入输出流
OutputStreamou=socket.getOutputStream();
BufferedReaderbff=newBufferedReader(newInputStreamReader(socket.getInputStream()));
//读取发来服务器信息
Stringline=null;
buffer="";
while((line=bff.readLine())!=null){
buffer=line+buffer;
}
//向服务器发送信息
ou.write(txt1.getBytes("gbk"));
ou.flush();
bundle.putString("msg",buffer.toString());
msg.setData(bundle);
//发送消息修改UI线程中的组件
myHandler.sendMessage(msg);
//关闭各种输入输出流
bff.close();
ou.close();
socket.close();
}catch(SocketTimeoutExceptionaa){
//连接超时在UI界面显示消息
bundle.putString("msg","服务器连接失败!请检查网络是否打开");
msg.setData(bundle);
//发送消息修改UI线程中的组件
myHandler.sendMessage(msg);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
3、最后别忘记加网络权限
<uses-permissionandroid:name="android.permission.INTERNET"/>
源码下载:http://xiazai.jb51.net/201608/yuanma/android-socket(jb51.net).rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。