1、使用Socket进行两个手机之间的通信需要安装两个不同的代码文件:服务端和客户端 分别进行安装
2、创建局域网:两个手机同时连一个WiFi或者两个手机进行热点和WLAN连接
3、客户端连接另一个手机IP时把另一个手机的IP改成静态IP(3的第二种方法做这个步骤)
下面上代码分客户端的和服务端的,布局文件textview、Editview、Button不上代码了,不懂socket通信原理的可以在百度百科上查看
客户端:
1)、MianSocketClient.Java
public class MianSocketClient extends AppCompatActivity { private SocketClient client; private TextView txt; private EditText edit; private Button btn; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); txt=(TextView)findViewById ( R.id.textView ); edit=(EditText)findViewById ( R.id.edit ); btn=(Button)findViewById ( R.id.btn ); client=new SocketClient (); //服务端的IP地址和端口号 client.clintValue (this,"10.0.3.15" ,6666); //开启客户端接收消息线程 client.openClientThread (); /** * 发送消息 * */ btn.setOnClickListener ( new View.OnClickListener ( ) { @Override public void onClick(View v) { client.sendMsg ( edit.getText ().toString () ); } } ); /** * 接受消息 * **/ SocketClient.mHandler=new Handler ( ){ @Override public void handleMessage(Message msg) { txt.setText ( msg.obj.toString ()); Log.i ( "msghh",msg.obj.toString ()); } }; } }2)、SocketClient.java
public class SocketClient { private Socket client; private Context context; private int port; //IP private String site; //端口 private Thread thread; public static Handler mHandler; private boolean isClient=false; private PrintWriter out; private InputStream in; private String str; /** * @effect 开启线程建立连接开启客户端 * */ public void openClientThread(){ thread=new Thread ( new Runnable ( ) { @Override public void run() { try { /** * connect()步骤 * */ client=new Socket ( site,port ); // client.setSoTimeout ( 5000 );//设置超时时间 if (client!=null) { isClient=true; forOut(); forIn (); }else { isClient=false; Log.e ( "error","发送失败" ); } Log.i ( "hahah","site="+site+" ,port="+port ); }catch (UnknownHostException e) { e.printStackTrace (); Log.i ( "socket","6" ); }catch (IOException e) { e.printStackTrace (); Log.i ( "socket","7" ); } } } ); thread.start (); } /** * 调用时向类里传值 * */ public void clintValue(Context context,String site,int port) { this.context=context; this.site=site; this.port=port; } /** * @effect 得到输出字符串 * */ public void forOut() { try { out=new PrintWriter ( client.getOutputStream () ); }catch (IOException e){ e.printStackTrace (); Log.i ( "socket","8" ); } } /** * @steps read(); * @effect 得到输入字符串 * */ public void forIn(){ while (isClient) { try { in=client.getInputStream (); /**得到的是16进制数,需要进行解析*/ byte[] bt = new byte[50]; in.read ( bt ); str=new String ( bt,"UTF-8" ); } catch (IOException e) {} if (str!=null) { Message msg = new Message ( ); msg.obj =str ; mHandler.sendMessage ( msg ); } } } /** * @steps write(); * @effect 发送消息 * */ public void sendMsg(final String str) { new Thread ( new Runnable ( ) { @Override public void run() { if (client!=null) { out.print ( str ); out.flush (); Log.i ( "outtt",out+"" ); }else { isClient=false; Log.e("error","网络连接失败"); } } } ).start (); } }服务端:
1)、MianActivity.java 之前取的名字没有改 应该改成MainSocketServer.java
public class MainActivity extends AppCompatActivity { private TextView txt; private EditText edit; private Button btn; /**启动服务端端口 * 服务端IP为手机IP * */ private SocketServer server=new SocketServer ( 6666 ); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); txt = (TextView) findViewById ( R.id.textView ); edit = (EditText) findViewById ( R.id.edit ); btn = (Button) findViewById ( R.id.btn ); /**socket服务端开始监听*/ server.beginListen ( ); btn.setOnClickListener ( new View.OnClickListener ( ) { @Override public void onClick(View v) { /**socket发送数据*/ server.sendMessage ( edit.getText ().toString () ); } } ); /**socket收到消息线程*/ SocketServer.ServerHandler=new Handler ( ){ @Override public void handleMessage(Message msg) { txt.setText ( msg.obj.toString ()); } }; } }2)、SocketServer.java
public class SocketServer { private ServerSocket server; private Socket socket; private InputStream in; private String str=null; private boolean isClint=false; public static Handler ServerHandler; /** * @steps bind();绑定端口号 * @effect 初始化服务端 * @param port 端口号 * */ public SocketServer(int port){ try { server= new ServerSocket ( port ); isClint=true; }catch (IOException e){ e.printStackTrace (); } } /** * @steps listen(); * @effect socket监听数据 * */ public void beginListen() { new Thread ( new Runnable ( ) { @Override public void run() { try { /** * accept(); * 接受请求 * */ socket=server.accept (); try { /**得到输入流*/ in =socket.getInputStream(); /** * 实现数据循环接收 * */ while (!socket.isClosed()) { byte[] bt=new byte[50]; in.read ( bt ); str=new String ( bt,"UTF-8" ); //编码方式 解决收到数据乱码 if (str!=null&&str!="exit") { returnMessage ( str ); }else if (str==null||str=="exit"){ break; //跳出循环结束socket数据接收 } System.out.println(str); } } catch (IOException e) { e.printStackTrace ( ); socket.isClosed (); } } catch (IOException e) { e.printStackTrace ( ); socket.isClosed (); } } } ).start (); } /** * @steps write(); * @effect socket服务端发送信息 * */ public void sendMessage(final String chat) { Thread thread=new Thread ( new Runnable ( ) { @Override public void run() { try { PrintWriter out=new PrintWriter ( socket.getOutputStream () ); out.print ( chat ); out.flush (); } catch (IOException e) { e.printStackTrace ( ); } } } ); thread.start (); } /** * @steps read(); * @effect socket服务端得到返回数据并发送到主界面 * */ public void returnMessage(String chat){ Message msg=new Message (); msg.obj=chat; ServerHandler.sendMessage ( msg ); } }这样就完成了,如果再有疑问就问我吧
实现了两个真机的简单通信
客户端代码:https://git.oschina.net/zhanglihow/SocketClient
服务端代码:https://git.oschina.net/zhanglihow/SocketServer
原文:http://blog.csdn.net/guang_liang_/article/details/52853134