怎么在android中利用Socket实现一个聊天小程序

发布时间:2020-12-07 15:34:19 作者:Leah
来源:亿速云 阅读:129

本篇文章为大家展示了怎么在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() 

上述内容就是怎么在android中利用Socket实现一个聊天小程序,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在微信小程序中利用websocket实现一个聊天功能
  2. 怎么在Java中使用Socket编写一个聊天程序

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android socket roi

上一篇:jshell如何在java9项目中使用

下一篇:利用Java怎么将数字日期翻译成英文单词

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》