安卓socket一对一聊天小demo(1)

60 阅读5分钟

Thread.sleep(200);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}.start();

}

/**

  • 接收来自客户端的消息

  • json数组包括socketID,msg

  • @author Administrator

*/

public class SocketThread extends Thread {

public int socketID;

public Socket socket;

public BufferedWriter writer;

public BufferedReader reader;

public SocketThread(Socket socket, int count) {

socketID = count;

this.socket = socket;

System.out.println("新增一台客户机,socketID:"+socketID);

}

@Override

public void run() {

super.run();

try {

reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));

writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));

while(isStartServer) {

if(reader.ready()) {

String data = reader.readLine();

JSONObject json = new JSONObject(data);

SocketMessage msg = new SocketMessage();

msg.to = json.getInt("to");

msg.msg = json.getString("msg");

msg.from = socketID;

msg.time = getTime(System.currentTimeMillis());

mMsgList.add(msg);

System.out.println("收到一条消息:"+json.getString("msg")+" >>>> to socketID:"+json.getInt("to"));

}

Thread.sleep(100);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

  • 得到此刻的时间

  • @param millTime

  • @return

*/

private String getTime(long millTime) {

Date d = new Date(millTime);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(sdf.format(d));

return sdf.format(d);

}

public static void main(String[] args) {

MyServer server = new MyServer();

server.startSocket();

}

}

2、安卓实现


(1)先来看看manifest:

<manifest xmlns:android="schemas.android.com/apk/res/and…"

package="com.jw.socketclient"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="com.jw.socketclient.MainActivity"

android:label="@string/app_name" >

(2)用到的依赖:

implementation 'androidx.legacy:legacy-support-v4:1.0.0'

implementation 'androidx.recyclerview:recyclerview:1.1.0'

(3)界面:

activity_main.xml

<LinearLayout xmlns:android="schemas.android.com/apk/res/and…"

xmlns:tools="schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

android:orientation="vertical" >

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content">

<Button

android:id="@+id/start_btn"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_weight="1"

android:text="start"/>

<Button

android:id="@+id/stop_btn"

android:text="stop"

android:layout_weight="1"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

<EditText

android:id="@+id/socket_id_edt"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="socketID"/>

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/rv"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="50dp"

android:background="#E3ECE3"

<EditText

android:id="@+id/msg_edt"

android:layout_marginLeft="30dp"

android:layout_marginRight="10dp"

android:layout_width="160dp"

android:layout_height="40dp"

android:background="#ffffff"

android:layout_gravity="center"

android:layout_weight="9"

/>

<Button

android:id="@+id/send_btn"

android:layout_width="40dp"

android:layout_height="35dp"

android:text="发送"

android:textColor="#ffffff"

android:layout_gravity="center"

android:background="#0B9C10"

android:layout_weight="1"/>

item.xml(右边的界面,展示自己发出的消息)

<LinearLayout xmlns:android="schemas.android.com/apk/res/and…"

xmlns:tools="schemas.android.com/tools"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:padding="6dp"

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center_horizontal"

android:orientation="vertical" >

<TextView

android:id="@+id/tv_time"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#ECE8E8"

android:padding="2dp"

android:textColor="#ffffff"

android:textSize="12sp" />

<RelativeLayout

android:layout_marginTop="5dp"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

<ImageView

android:id="@+id/iv_userhead"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_alignParentRight="true"

android:background="@drawable/head_img"

android:focusable="false" />

<TextView

android:id="@+id/tv_name"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_toRightOf="@id/iv_userhead"

android:textColor="#818181"

android:textSize="15sp" />

<TextView

android:id="@+id/tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginRight="10dp"

android:layout_toLeftOf="@id/iv_userhead"

android:clickable="true"

android:focusable="true"

android:lineSpacingExtra="2dp"

android:minHeight="50dp"

android:gravity="center"

android:background="@drawable/chat_to"

android:textColor="#ff000000"

android:textSize="15sp" />

item2.xml(左边界面,展示别人发过来的消息)

<LinearLayout xmlns:android="schemas.android.com/apk/res/and…"

xmlns:tools="schemas.android.com/tools"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:padding="6dp"

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="vertical" >

<TextView

android:id="@+id/tv_time2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#ECE8E8"

android:padding="2dp"

android:textColor="#ffffff"

android:textSize="12sp" />

<RelativeLayout

android:layout_marginTop="5dp"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

<ImageView

android:id="@+id/iv_userhead2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:background="@drawable/feedback"

android:focusable="false" />

<TextView

android:id="@+id/tv_name2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_toLeftOf="@id/iv_userhead2"

android:textColor="#818181"

android:textSize="15sp"

android:layout_alignParentLeft="true"

/>

<TextView

android:id="@+id/tv2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="10dp"

android:layout_toRightOf="@id/iv_userhead2"

android:clickable="true"

android:focusable="true"

android:gravity="center"

android:lineSpacingExtra="2dp"

android:minHeight="50dp"

android:background="@drawable/chat_from"

android:textColor="#ff000000"

android:textSize="15sp"

/>

(4)4张图,随便网上下载几张矢量图即可。


在这里插入图片描述

(5)活动:


MainActivity.java

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import org.json.JSONObject;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.EditText;

import android.app.Activity;

import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends Activity implements OnClickListener {

private EditText mSocketIDEdt, mMessageEdt;

private StringBuffer mConsoleStr = new StringBuffer();

private Socket mSocket;

private boolean isStartRecieveMsg;

private RecyclerView rv;

private SocketHandler mHandler;

protected BufferedReader mReader;

protected BufferedWriter mWriter;

private static final int COMPLETED = 1;

private ArrayList list;

private MyAdapter adapter;

Thread thread;

private static boolean flag=false;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initView();

}

private void initView() {

mSocketIDEdt = (EditText) findViewById(R.id.socket_id_edt);

mMessageEdt = (EditText) findViewById(R.id.msg_edt);

findViewById(R.id.start_btn).setOnClickListener(this);

findViewById(R.id.send_btn).setOnClickListener(this);

findViewById(R.id.stop_btn).setOnClickListener(this);

mHandler = new SocketHandler();

rv = (RecyclerView) findViewById(R.id.rv);

list = new ArrayList<>();

adapter = new MyAdapter(this);

rv.setAdapter(adapter);

LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

rv.setLayoutManager(manager);

}

private void initSocket() {

thread = new Thread(new Runnable() {

@Override

public void run() {

try {

isStartRecieveMsg = true;

mSocket = new Socket("192.168.2.172", 2000);

mReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "utf-8"));

mWriter = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "utf-8"));

while(isStartRecieveMsg) {

if(mReader.ready()) {

mHandler.obtainMessage(0, mReader.readLine()).sendToTarget();

}

Thread.sleep(200);

}

mWriter.close();

mReader.close();

mSocket.close();

} catch (Exception e) {

e.printStackTrace();

}

}

});

thread.start();

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.send_btn:

send();

break;

case R.id.start_btn:

if(!isStartRecieveMsg) {

initSocket();

}

break;

case R.id.stop_btn:

flag=true;

System.err.println("中断");

default:

break;

}

}

private void send() {

new AsyncTask<String, Integer, String>() {

@Override

protected String doInBackground(String... params) {

sendMsg();

return null;

}

}.execute();

}

protected void sendMsg() {

try {

String socketID = mSocketIDEdt.getText().toString().trim();

String msg = mMessageEdt.getText().toString().trim();

JSONObject json = new JSONObject();

json.put("to", socketID);

json.put("msg", msg);

mWriter.write(json.toString()+"\n");

mWriter.flush();

mConsoleStr.append("我" +msg+" "+getTime(System.currentTimeMillis())+"\n");

MyBean bean = new MyBean("我",2,msg,getTime(System.currentTimeMillis()));

list.add(bean);

/**

  • 在子线程更新UI

*/

Message message = new Message();

message.what = COMPLETED;

mHandler.sendMessage(message);

} catch (Exception e) {

e.printStackTrace();

}

}

class SocketHandler extends Handler {

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

super.handleMessage(msg);

switch (msg.what) {

case 0:

try {

JSONObject json = new JSONObject((String)msg.obj);

MyBean bean = new MyBean(json.getString("from"),1,json.getString("msg"),getTime(System.currentTimeMillis()));

list.add(bean);

} catch (Exception e) {

e.printStackTrace();

}

// 向适配器set数据

adapter.setData(list);

rv.setAdapter(adapter);

LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

rv.setLayoutManager(manager);

rv.scrollToPosition(adapter.getItemCount()-1);//recycleview滑到底部

break;

case 1:

// 向适配器set数据

adapter.setData(list);

rv.setAdapter(adapter);

manager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

rv.setLayoutManager(manager);

rv.scrollToPosition(adapter.getItemCount()-1);//recycleview滑到底部

break;

default:

break;

}

}

}

@Override

public void onBackPressed() {

super.onBackPressed();

isStartRecieveMsg = false;

}

private String getTime(long millTime) {

Date d = new Date(millTime);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(sdf.format(d));

return sdf.format(d);

}

}

(6)适配器:


MyAdapter.java

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter {

private Context context;

private ArrayList data;

private static final int TYPEONE = 1;

private static final int TYPETWO = 2;

public MyAdapter(Context context) {

this.context = context;

}

public void setData(ArrayList data) {

this.data = data;

notifyDataSetChanged();

}

@Override

public int getItemViewType(int position) {

return data.get(position).getNumber();

}

@Override

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

RecyclerView.ViewHolder holder = null;

switch (viewType){

case TYPEONE:

View view = LayoutInflater.from(context).inflate(R.layout.item2,parent,false);

holder = new OneViewHolder(view);

break;

case TYPETWO:

View view1 = LayoutInflater.from(context).inflate(R.layout.item,parent,false);

holder = new TwoViewHolder(view1);

break;

}

文末

初级工程师拿到需求会直接开始做,然后做着做着发现有问题了,要么技术实现不了,要么逻辑有问题。

而高级工程师拿到需求会考虑很多,技术的可行性?对现有业务有没有帮助?对现有技术架构的影响?扩展性如何?等等...之后才会再进行设计编码阶段。

而现在随着跨平台开发,混合式开发,前端开发之类的热门,Android开发者需要学习和掌握的技术也在不断的增加。

通过和一些行业里的朋友交流讨论,以及参考现在大厂面试的要求。我们花了差不多一个月时间整理出了这份Android高级工程师需要掌握的所有知识体系。你可以看下掌握了多少。

混合式开发,微信小程序。都是得学会并且熟练的

这些是Android相关技术的内核,还有Java进阶

高级进阶必备的一些技术。像移动开发架构项目实战等

Android前沿技术;包括了组件化,热升级和热修复,以及各种架构跟框架的详细技术体系

以上即是我们整理的Android高级工程师需要掌握的技术体系了。可能很多朋友觉得很多技术自己都会了,只是一些新的技术不清楚而已。应该没什么太大的问题。

而这恰恰是问题所在!为什么别人高级工程师能年限突破30万,而你只有十几万呢?

就因为你只需补充你自己认为需要的,但并不知道企业需要的。这个就特别容易造成差距。因为你的技术体系并不系统,是零碎的,散乱的。那么你凭什么突破30万年薪呢?

我这些话比较直接,可能会戳到一些人的玻璃心,但是我知道肯定会对一些人起到点醒的效果的。而但凡只要有人因为我的这份高级系统大纲以及这些话找到了方向,并且付出行动去提升自我,为了成功变得更加努力。那么我做的这些就都有了意义。

喜欢的话请帮忙转发点赞一下能让更多有需要的人看到吧。谢谢!

以上系统大纲里包含的所有技术资料,我这里都有的。可以免费分享给有需要的朋友!

资料领取方式:点击我的GitHub