本文仅为个人学习笔记,个人学习分享

%title插图%num

idea服务端代码:
package lrz.server;
import lrz.data.NetFileData;

import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

public class ServerSocket01 {
int port = 8019;// 自定义一个端口,端口号尽可能挑选一些不被其他服务占用的端口,祥见http://blog.csdn.net/hsj521li/article/details/7678880
static int connect_count = 0;// 连接次数统计
ArrayList<String> msgBackList;

public ServerSocket01() {
// TODO Auto-generated constructor stub
}

public ServerSocket01(int port) {
super();
this.port = port;
}

private void printLocalIp(ServerSocket serverSocket) {// 枚举打印服务端的IP
try {
System.out.println(“服务端命令端口prot=” + serverSocket.getLocalPort());
Enumeration<NetworkInterface> interfaces = null;
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresss = ni.getInetAddresses();
while (addresss.hasMoreElements()) {
InetAddress nextElement = addresss.nextElement();
String hostAddress = nextElement.getHostAddress();
System.out.println(“本机IP地址为:” + hostAddress);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void work() throws IOException {
// 注意:由于Socket的工作是阻塞式,Android端Socket的工作必须在新的线程中实现,若在UI主线程中工作会报错

ServerSocket serverSocket = new ServerSocket(port);
printLocalIp(serverSocket);
while (true) {// 无限循环,使之能结束当前socket服务后,准备下一次socket服务

System.out.println(“Waiting client to connect…..”);
Socket socket = serverSocket.accept();// 阻塞式,直到有客户端连接进来,才会继续往下执行,否则一直停留在此代码
System.out.println(“Client connected from: ”
+ socket.getRemoteSocketAddress().toString());

// eclipse 快捷键
// alt+/ 代码补全
// ctr+1 代码修正
// ctr+2,L 命名给局部变量

// TODO: As follows:

// 实现读客户端发送过来的命令,例如实现private ArrayList<String> readSocketMsg(Socket socket) throws IOException函数
// 调用 ArrayList<String> cmdList=readSocketMsg(socket);
// 定义一个全局变量 ArrayList<String> msgBackList,供服务端处理命令,并将返回结果赋值给msgBackList
// msgBackList=dealCmd(cmdList);//处理命令,例如dir命令,并将处理结果给msgBackList
// 实现服务端写回数据函数 private void writebackMsg(Socket socket) throws IOException
// 将msgBackList按规定的格式写回给客户端
// 实现 private void close(Socket socket) throws IOException,关闭socket
// 调用 close(socket);
ArrayList<String> cmdList=readSocketMsg(socket);

cmdList.forEach(s -> System.out.println(s));

String cmdbody=cmdList.get(0);
try {
msgBackList= exeDir(cmdbody);
} catch (Exception e) {
e.printStackTrace();
}
msgBackList.forEach(s -> System.out.println(s));
writeBackMsg(socket);
socket.close();
System.out.println(“当前Socket服务结束”);

}
}
public ArrayList<String> readSocketMsg(Socket socket) throws IOException {
// 读socket的输入流,传入的socket参数是已经连接成功未处于关闭的socket
//首先读取一行,并将读取的字符串内容转换为int型数据,已获得后续需要读取的行数
ArrayList<String> msgList=new ArrayList<String>();
InputStream inputStream = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream, “utf-8″);
BufferedReader bufferedReader=new BufferedReader(reader);
String lineNumStr = bufferedReader.readLine();
int lineNum=Integer.parseInt(lineNumStr);
for(int i=0;i<lineNum;i++){
String str = bufferedReader.readLine();
msgList.add(str);
}
//读取结束后,输入流不能关闭,此时关闭,会将socket关闭,从而导致后续对socket写操作无法实现
return msgList;
}
private void writeBackMsg(Socket socket) throws IOException {
// TODO Auto-generated method stub
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());//socket.getOutputStream()是输出流,BufferedOutputStream则将其封装为带缓冲的输出流
OutputStreamWriter writer=new OutputStreamWriter(os,”UTF-8″);//尝试将字符编码改成”GB2312”
writer.write(“”+msgBackList.size()+”\n”);//未真正写入的输出流,仅仅在内存中
writer.flush();//写入输出流,真正将数据传输出去
// OutputStreamWriter writer=new OutputStreamWriter(os);//默认的字符编码,有可能是GB2312也有可能是UTF-8,取决于系统
// //建议不要用默认字符编码,而是指定UTF-8,以保证发送接收字符编码一致,不至于出乱码
//输出流是字节传输的,还不具备字符串直接写入功能,因此再将其封装入OutputStreamWriter,使其支持字符串直接写入
for(int i=0;i<msgBackList.size();i++){
writer.write(msgBackList.get(i)+”\n”);
writer.flush();
}
}

private ArrayList<String> exeDir(String cmdBody) throws Exception {
// TODO Auto-generated method stub
ArrayList<String> backList=new ArrayList<String>();

File file = new File(cmdBody);
File[] listFiles = file.listFiles();
for(File mfile:listFiles){
String fileName = mfile.getName();
long lastModified = mfile.lastModified();//获取文件修改时间
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//给时间格式,例如:2018-03-16 09:50:23
String fileDate = dateFormat.format(new Date(lastModified));//取得文件*后修改时间,并按格式转为字符串
String fileSize=”0″;
String isDir=”1″;
if(!mfile.isDirectory()){//判断是否为目录
isDir=”0″;
fileSize=””+mfile.length();
}
backList.add(fileName+”>”+fileDate+”>”+fileSize+”>”+isDir+”>”);
}
return backList;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new ServerSocket01().work();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
android stdio客户端代码:
MainActivity.java

package com.example.sockettest.app;

import androidx.appcompat.app.AppCompatActivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sockettest.R;
import com.example.sockettest.SocketClient;
import com.tbruyelle.rxpermissions2.RxPermissions;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

public static final String KEY_SERVER_ACK_MSG = “KEY_SERVER_ACK_MSG”;
private Handler handler = null;
EditText url,way,dir;
TextView tv;
Button submit;
SocketClient socketClient=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

url=findViewById(R.id.url);
way=findViewById(R.id.way);
dir=findViewById(R.id.dir);
tv=findViewById(R.id.tv);
submit=findViewById(R.id.submit);

handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
Bundle data_bundle = msg.getData();
ArrayList<String> data=data_bundle.getStringArrayList(KEY_SERVER_ACK_MSG);
tv.setText(data.toString());
return false; }
});

submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int port=Integer.parseInt(way.getText().toString());
socketClient=new SocketClient(url.getText().toString(),port,handler);
socketClient.work(dir.getText().toString());
}
});

}

}
activity_main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<EditText
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”3″
android:id=”@+id/url”
android:text=”10.218.216.10″/>
<EditText
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”3″
android:id=”@+id/way”
android:text=”8019″/>

</LinearLayout>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/dir”
android:text=”d://”/>
<Button
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”submit”
android:id=”@+id/submit”/>

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/tv”
android:text=”show”/>
</LinearLayout>
SocketClient.java

package com.example.sockettest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;

public class SocketClient {
private String ip;
private int port;
private ArrayList<String> cmd;
private int time_out=10000;
private Handler handler;
private Socket socket;
public static final String KEY_SERVER_ACK_MSG = “KEY_SERVER_ACK_MSG”;
private OutputStreamWriter writer;
private BufferedReader bufferedReader;
public SocketClient(String ip, int port, Handler handler) {
this.port = port;
this.ip = ip;
this.handler = handler;
}
private void connect() throws IOException {
InetSocketAddress address=new InetSocketAddress(ip,port);
socket=new Socket();
socket.connect(address,time_out);
}
private void writeCmd(String cmd) throws IOException {
BufferedOutputStream os=new BufferedOutputStream(socket.getOutputStream());
writer=new OutputStreamWriter(os,”UTF-8″);
writer.write(“1\n”);
writer.write(cmd+”\n”);
writer.flush();
}
private ArrayList<String> readSocketMsg() throws IOException {
ArrayList<String> msgList=new ArrayList<>();
InputStreamReader isr=new InputStreamReader(socket.getInputStream(),”UTF-8″);
bufferedReader=new BufferedReader(isr);
String numStr = bufferedReader.readLine();
int linNum = Integer.parseInt(numStr);
for (int i = 0; i <linNum ; i++) {
String s = bufferedReader.readLine();
msgList.add(s);
}
return msgList;
}
private void close() throws IOException {
bufferedReader.close();
writer.close();
socket.close();
}
private void doCmdTask(String cmd){
ArrayList<String> msgList=new ArrayList<>();
try {
connect();
writeCmd(cmd);
msgList = readSocketMsg();
close();
} catch (IOException e) {
e.printStackTrace();
}
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putStringArrayList(KEY_SERVER_ACK_MSG,msgList);
message.setData(bundle);
handler.sendMessage(message);

}
public void work(final String cmd){
new Thread(new Runnable() {
@Override
public void run() {
doCmdTask(cmd);
}
}).start();
}
}