欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

android Socket实现简单聊天小程序

时间:2020-12-03 17:44:17|栏目:Android代码|点击:

android Socket实现简单聊天小程序,供大家参考,具体内容如下

服务器端:

package org.hwq.echo; 
 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 
 
public class TalkServer { 
  public static void main(String[] args) throws IOException{ 
    ServerSocket server = null; 
    Socket client = null; 
    BufferedReader in = null; 
    PrintWriter out = null; 
    try{ 
      server = new ServerSocket(4700); 
      client = server.accept(); 
      out = new PrintWriter(client.getOutputStream()); 
      in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
      String line = in.readLine(); 
      while(!"bye".equals(line)){ 
        System.out.println("client:"+line); 
        out.println("echo:"+line); 
        out.flush(); 
        line = in.readLine(); 
      } 
    }catch (Exception e) { 
      e.printStackTrace(); 
      if(client !=null) 
        client.close(); 
      if(server != null) 
        server.close(); 
    } 
  } 
} 

手机端:

package org.hwq.cho; 
 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.net.UnknownHostException; 
 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
 
public class EchoActivity extends Activity implements OnClickListener { 
  EditText show,msg; 
  Button send; 
  Handler handler; 
  Socket client; 
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    handler = new MyHandler(); 
    show = (EditText) findViewById(R.id.show); 
    msg = (EditText) findViewById(R.id.msg); 
    send = (Button) findViewById(R.id.send); 
    send.setOnClickListener(this); 
  } 
  @Override 
  public void onClick(View arg0) { 
    String message = msg.getText().toString(); 
//   System.out.println("msg:"+message); 
    new EchoThread(EchoActivity.this,message).start(); 
  } 
  public class MyHandler extends Handler{ 
    @Override 
    public void handleMessage(Message msg) { 
      switch(msg.what){ 
      case 1: 
        Toast.makeText(EchoActivity.this, "建立连接失败", 0).show(); 
        break; 
      case 2: 
        String message = (String) msg.obj; 
        System.out.println("Handler:"+message); 
        show.append("\n"+message); 
        break; 
      } 
    } 
  } 
  private class EchoThread extends Thread{ 
    private Context context; 
    private String msg; 
    EchoThread(Context context,String msg){ 
      this.context = context; 
      this.msg = msg; 
    } 
    public void run(){ 
      if(client == null){ 
        try { 
          client = new Socket("192.168.1.102",4700); 
        } catch (IOException e) { 
          Message message = new Message(); 
          message.what = 1; 
          handler.sendMessage(message); 
        } 
      } 
      System.out.println("建立连接"); 
      try{ 
        BufferedReader in; 
        BufferedReader input; 
        PrintWriter out; 
        in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
        out = new PrintWriter(client.getOutputStream()); 
        String line = msg; 
        if(!"bye".equals(line)){ 
          System.out.println("line:"+line); 
          out.println(line); 
          out.flush(); 
          String echo = in.readLine(); 
          System.out.println("server:"+echo); 
          Message message = new Message(); 
          message.obj = echo; 
          message.what = 2; 
          handler.sendMessage(message); 
        } 
      }catch (Exception e) { 
         
      } 
    } 
  } 
} 

注意几点:

1、添加网络权限

<uses-permission android:name="android.permission.INTERNET"/> 

如果没添加,无法使用socket连接网络。
2、在新启线程中不要使用android系统UI界面
在EchoThrad的run()方法里面,有下面代码:

if(client == null){ 
        try { 
          client = new Socket("192.168.1.102",4700); 
        } catch (IOException e) { 
          Message message = new Message(); 
          message.what = 1; 
          handler.sendMessage(message); 
        } 
      } 

这里的handler.sendMessage(message);是发送一个消息给handler,然后handler根据消息弹出一个Toast显示连接失败。如果这里直接使用

Toast.makeText(EchoActivity.this, "建立连接失败", 0).show(); 

会报如下错:

Can't create handler inside thread that has not called Looper.prepare() 

上一篇:studio碰到问题:java.lang.UnsatisfiedLinkError解决办法

栏    目:Android代码

下一篇:android ListActivity显示图标实例

本文标题:android Socket实现简单聊天小程序

本文地址:http://www.codeinn.net/misctech/29048.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有