冲刺十五天
Posted xiaofengzai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了冲刺十五天相关的知识,希望对你有一定的参考价值。
实现链接数据库端的朋友信息展示以及Socket通信学习
链接数据库的朋友信息并展示
package com.example.newbsh.UI.friends; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.example.newbsh.HttpUtil.HttpUtil; import com.example.newbsh.MainActivity; import com.example.newbsh.R; import com.example.newbsh.UI.friends.list.SideBar; import com.example.newbsh.UI.friends.list.SortAdapter; import com.example.newbsh.UI.friends.list.User; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.Collections; public class FriendFragment extends Fragment { private FriendViewModel mViewModel; private View view; private ListView listView; private SideBar sideBar; private ArrayList<User> list; private Handler handler; private String getUsername(){ return MainActivity.getUserName(); } public static FriendFragment newInstance() { return new FriendFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view=inflater.inflate(R.layout.friend_fragment, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(FriendViewModel.class); // TODO: Use the ViewModel initView(); getThreadData(); handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { //线程回调更新数据 if (msg.what == 200) { list=new ArrayList<>(); JSONArray jsonArray=(JSONArray)msg.obj; for(int i=0;i<jsonArray.length();i++) { try { String friendname= (String) jsonArray.getJSONObject(i).get("friendname"); String friendurl= (String) jsonArray.getJSONObject(i).get("friendurl"); User bean=new User(friendname,friendurl); list.add(bean); } catch (JSONException e) { e.printStackTrace(); } } Collections.sort(list); // 对list进行排序,需要让User实现Comparable接口重写compareTo方法 SortAdapter adapter = new SortAdapter(view.getContext(), list); listView.setAdapter(adapter); } return true; } }); } private void initView() { listView = (ListView) view.findViewById(R.id.listView); sideBar = (SideBar) view.findViewById(R.id.side_bar); sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() { @Override public void onSelectStr(int index, String selectStr) { for (int i = 0; i < list.size(); i++) { if (selectStr.equalsIgnoreCase(list.get(i).getFirstLetter())) { listView.setSelection(i); // 选择到首字母出现的位置 return; } } } }); } private void getThreadData() { //线程封装网络请求 new Thread(new Runnable() { @Override public void run() { String reqdata = ""; String address="http://39.97.181.86/BaiXiaoSheng/myfriend?username="+getUsername(); try { final JSONArray json = new JSONArray(String.valueOf(HttpUtil.sendPost(address, reqdata))); Log.d("tag", json.toString()); Message msg = new Message(); msg.what = 200; msg.obj = json; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }
Socket通信与本地服务器端链接
服务器端:
package servlet; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.security.Provider; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server { private static final int PORT=12345; private List<Socket> mlist=new ArrayList<>(); private ServerSocket server=null; private ExecutorService myExecutorService=null; public static void main(String[] args){ new Server(); } public Server() { try { server=new ServerSocket(PORT); //创建线程池 myExecutorService=Executors.newCachedThreadPool(); System.out.println("服务端运行中... "); Socket client=null; while(true) { client=server.accept(); mlist.add(client); myExecutorService.execute(new Service(client)); } }catch (Exception e){ e.printStackTrace(); } } class Service implements Runnable { private Socket socket; private BufferedReader in = null; private String msg = ""; public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); msg = "用户:" +this.socket.getInetAddress() + "~加入了聊天室" +"当前在线人数:" +mlist.size(); this.sendmsg(); }catch(IOException e){e.printStackTrace();} } @Override public void run() { try{ while (true) { if((msg=in.readLine())!=null) { if(msg.equals("bye")) { System.out.println("~~~~~~~~~~~"); mlist.remove(socket); in.close(); msg = "用户:" + socket.getInetAddress() + "退出:" +"当前在线人数:"+mlist.size(); socket.close(); this.sendmsg(); break; } else { msg=socket.getInetAddress()+" 说:"+msg; this.sendmsg(); } } } }catch (Exception e){ e.printStackTrace(); } } //为连接上服务端的每个客户端发送信息 public void sendmsg() { System.out.println(msg); int num = mlist.size(); for(int index = 0;index < num;index++) { Socket mSocket = mlist.get(index); PrintWriter pout = null; try { pout = new PrintWriter(new BufferedWriter( new OutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true); pout.println(msg); }catch (IOException e) {e.printStackTrace();} } } } }
安卓端:
package com.example.sockettest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; public class SocketActivity extends AppCompatActivity implements Runnable { //定义相关变量,完成初始化 private TextView txtshow; private EditText editsend; private Button btnsend; private static final String HOST = "192.168.137.1"; private static final int PORT = 12345; private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; private StringBuilder sb = null; //定义一个handler对象,用来刷新界面 public Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x123) { sb.append(content); txtshow.setText(sb.toString()); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_socket); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } sb = new StringBuilder(); txtshow = (TextView) findViewById(R.id.txtshow); editsend = (EditText) findViewById(R.id.editsend); btnsend = (Button) findViewById(R.id.btnsend1); //当程序一开始运行的时候就实例化Socket对象,与服务端进行连接,获取输入输出流 //因为4.0以后不能再主线程中进行网络操作,所以需要另外开辟一个线程 new Thread() { public void run() { try { socket = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())), true); } catch (IOException e) { e.printStackTrace(); } } }.start(); new Thread(new Runnable() { @Override public void run() { btnsend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = editsend.getText().toString(); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(msg); } } } }); } }).start(); //为发送按钮设置点击事件 new Thread(SocketActivity.this).start(); } //重写run方法,在该方法中输入流的读取 @Override public void run() { try { while (true) { if (socket.isConnected()) { if (!socket.isInputShutdown()) { if ((content = in.readLine()) != null) { content += " "; handler.sendEmptyMessage(0x123); } } } } } catch (Exception e) { e.printStackTrace(); } } }
以上是关于冲刺十五天的主要内容,如果未能解决你的问题,请参考以下文章