socket连接,传输文件,读写excel,txt,多线程处理请求

来源:互联网 发布:大数据分析硕士 编辑:程序博客网 时间:2024/05/16 16:12

        最近写了一个小程序,关于socket连接的,分为客户端和服务端,服务端在指定的端口等待客户端连接,针对不同的客户端建立一个线程去处理请求,客户端则想服务端建立连接,这个可以传输excel文件,也可以生成excel文件,具体看代码吧,注释的挺清楚的。。。

一共4个文件。SocketClient.java代表客户端对象,SockeServer.java代表服务端,Connection.java为多线程处理,ReaderWriterFile.java为处理读写文件的对象。

SocketClient.java

package socket;import java.io.*;import java.net.*;public class SocketClient {public Socket soc;// 与服务端连接的套接字对象public String host;// 连接到得主机public int port;// 端口public SocketClient(String host, int port) {super();this.host = host;this.port = port;}// 初始化public void init() {try {// 连接到指定的主机的指定端口soc = new Socket(host, port);System.out.println("connecting" + soc);System.out.println("连接到服务器。。。");} catch (UnknownHostException e) {// TODO Auto-generated catch blockSystem.out.println("未知服务器异常: " + e);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 进行连接处理public void connect() {try {// 封装从服务端的输入流BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));// 封装到服务端的输出流PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())), true);// 从服务端收到的信息String receive_msg = in.readLine();System.out.println("服务器说:" + receive_msg);// 封装控制台输入流BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));// 不断的与服务端进行交互,直到客户端输入了quitwhile (true) {// 从控制台读取数据String send_msg = stdin.readLine().trim();// 将读取的数据发送到服务端out.println(send_msg);// 如果输入离开则断开连接,释放资源if ("quit".equals(send_msg)) {try {in.close();out.close();} catch (IOException e) {System.out.println("socket关闭异常。。" + e);}break;}// 如果是请求文件if (send_msg.trim().startsWith("get")) {System.out.println("从服务端获取的文件内容如下:");// 将读取到的所有字符串StringBuffer穿起来receive_msg = null;StringBuffer result = new StringBuffer();// 不断获取文件内容,直到遇到文件传输结束标志(end的md5的16位加密结果)while (!(receive_msg = in.readLine()).equals("15b86f2d013b2618")) {result.append(receive_msg + "\n");}System.out.println(result.toString() + "\n文件读取结束!");// 输出生成word文件new ReaderWriterFile().writeTxt(result.toString(),"d:/out.docx");System.out.println("输出d:/out.docx文件成功!");} else {// 否则直接打印获得的信息zSystem.out.println(in.readLine());}}System.out.println("客户端要离开了...");} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("有IO异常:" + e);}}public String getFileContents(BufferedReader inreader) {StringBuffer result = new StringBuffer();try {String tmp = null;while ((tmp = inreader.readLine()) != null) {result.append(tmp + "\n");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return result.toString();}// 关闭连接释放资源public void close() {try {soc.close();} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("socket关闭异常。。" + e);}}public static void main(String[] args) {SocketClient client = new SocketClient("127.0.0.1", 5005);client.init();client.connect();client.close();}}

SocketServer.java

package socket;import java.net.*;import java.io.*;public class SocketServer {// 服务端的socketpublic ServerSocket svrsoc = null;// 与客户端连接的socketpublic Socket soc = null;// 服务端监听的端口public int port = 0;public int max = 0;public SocketServer(int port, int max) {this.port = port;this.max = max;}public SocketServer(int port) {this.port = port;}// 初始化public void init() {for (int i = 0; i < max; i++) {ConnectionProcesser processer = new ConnectionProcesser();new Thread(processer, "第" + i + "个线程").start();}}// 处理客户端请求public void process() {try {svrsoc = new ServerSocket(port);System.out.println("初始化:" + svrsoc);int number = 1;// 不断在port上等待客户端的请求,并新建一个线程处理每个客户端while (true) {soc = svrsoc.accept();System.out.println("第" + number + "个用户连接到服务器了!");System.out.println("Connecting:" + soc);// 新建线程处理请求new Connection(soc, number).start();number++;}} catch (IOException e) {System.out.println("出IO异常了,error:" + e);}}// 关闭连接释放资源public void close() {try {svrsoc.close();} catch (IOException e) {System.err.println("异常来了!" + e);}}// 入口方法public static void main(String args[]) throws IOException {SocketServer server = new SocketServer(5005);server.process();server.close();}}


Connection.java

package socket;import java.net.*;import java.io.*;public class Connection extends Thread {// 与客户端连接的socketpublic Socket soc = null;// 连接的数量public int count;public Connection(Socket soc, int count) {super();this.soc = soc;this.count = count;}@Overridepublic void run() {try {// 封装从客户端发来的输入流BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));// 封装到客户端的输出流PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())), true);// 获取客户端的IP和端口InetAddress clientIP = soc.getInetAddress();System.out.println("第" + count + "个客户端IP:" + clientIP);int port = soc.getPort();System.out.println("第" + count + "个客户端端口是:" + port);// 向客户端发送消息out.println("欢迎光临!!客户端您可以进行多次请求,输入quit可以结束本次连接。请求(传输)文件的命令格式如下:get abc.txt|xls");while (true) {// 读取传过来的信息String str = in.readLine();// 如果什么都没有输入if (str.equals("") || str == null) {out.println("你什么都没输入,请重新输入内容!!!");continue;} else {// 如果要断开连接了,释放资源if (str.trim().equals("quit")) {System.out.println("第" + count + "个客户端离开啦!");in.close();out.close();break;}// 如果是获取文件的请求if (str.trim().startsWith("get")) {// 用" "分割获取文件名,分割后最后一个数组元素即为文件名String[] temp = str.trim().split(" ");String filename = temp[temp.length - 1];// 用.分割文件名中的格式String gs[] = filename.split("\\.");String geshi = gs[gs.length - 1];// 创建文件读取对象ReaderWriterFile reader = new ReaderWriterFile();String result = null;// 根据不同的文件请求,进行不同文件的读取if ("xls".equals(geshi)) {result = reader.readExcelFile(filename);} else if ("txt".equals(geshi)) {result = reader.readTxtFile(filename);}String[] rows = result.split("\n");// 将读取的文件内容分行发送到客户端中for (String res : rows) {out.println(res);}// 打印end的16位md5加密结果作为文件传输结束标志out.println("15b86f2d013b2618");} else {out.println("echo 客户端:" + str);}System.out.println("第" + count + "个客户端说:" + str);}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


ReaderWriter.java

package socket;import java.io.*;import org.apache.poi.hssf.usermodel.*;import org.apache.poi.poifs.filesystem.DirectoryEntry;import org.apache.poi.poifs.filesystem.DocumentEntry;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public class ReaderWriterFile {public String readTxtFile(String filename) {StringBuffer result = new StringBuffer();FileReader fileReader;try {// 读取文件内容fileReader = new FileReader(new File(filename));BufferedReader bufferedFileReader = new BufferedReader(fileReader);String line = null;// 逐行读取while ((line = bufferedFileReader.readLine()) != null) {result.append(line + "\n");}fileReader.close();} catch (FileNotFoundException e) {System.out.println("文件没找到哦。。" + e);} catch (IOException e) {System.out.println("有IO异常。。。" + e);}return result.toString();}public String readExcelFile(String filename) {StringBuffer result = new StringBuffer();String fileToBeRead = filename;// 创建对Excel工作簿文件的引用HSSFWorkbook workbook = null;try {workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));// 创建对工作表的引用。HSSFSheet sheet = workbook.getSheetAt(0);// HSSFSheet sheet = workbook.getSheet("Sheet1");// 读取左上端单元int row_num = sheet.getLastRowNum();for (int i = 0; i < row_num; i++) {HSSFRow r = sheet.getRow(i);int cell_num = r.getLastCellNum();for (int j = 0; j < cell_num; j++) {result.append((r.getCell((short) j).getStringCellValue())).append("\t");}result.append("\n");}} catch (FileNotFoundException e) {System.out.println("文件没找到 : " + e);} catch (IOException e) {System.out.println("已运行IO异常: " + e);}return result.toString();}public void writeExcel(String path, String content) {String outputFile = path;String data = content;try {// 创建新的Excel 工作簿HSSFWorkbook workbook = new HSSFWorkbook();// 在Excel工作簿中建一工作表,其名为缺省值HSSFSheet sheet = workbook.createSheet();String[] rows = data.split("\n");for (int i = 0; i < rows.length; i++) {HSSFRow row = sheet.createRow((short) i);String[] cells = rows[i].split("\t");for (int j = 0; j < cells.length; j++) {HSSFCell cell = row.createCell((short) j);cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setCellValue(cells[j]);}}// 新建一输出文件流FileOutputStream fOut = new FileOutputStream(outputFile);// 把相应的Excel 工作簿存盘workbook.write(fOut);fOut.flush();// 操作结束,关闭文件fOut.close();System.out.println(path + "文件生成完毕...");} catch (FileNotFoundException e) {System.out.println("文件没找到 : " + e);} catch (IOException e) {System.out.println("已运行IO异常 : " + e);}}public String readWordFile(String filename) {return "";}public boolean writeWordFile(String content, String path){boolean result = false;try {//byte[] a = new String("aaaaaa测试测试 hello word 你好").getBytes("gbk");byte[] a = content.getBytes("gbk");ByteArrayInputStream bs = new ByteArrayInputStream(a);POIFSFileSystem fs = new POIFSFileSystem();DirectoryEntry directory = fs.getRoot();DocumentEntry de = directory.createDocument("WordDocument", bs);// 以上两句代码不能省略,否则输出的是乱码FileOutputStream fos = new FileOutputStream(path);fs.writeFilesystem(fos);bs.close();fos.flush();fos.close();result = true;} catch (IOException e) {System.out.println("IO异常" + e);}return result;}public void writeTxt(String content, String path){File f = new File(path);try {FileWriter write = new FileWriter(f);BufferedWriter bf = new BufferedWriter(write);bf.write(content);//bf.close();write.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] arg) {ReaderWriterFile rw = new ReaderWriterFile();String res = rw.readExcelFile("E:/test.xls");System.out.println(res);rw.writeExcel("D:\\out.xls", res);}}

运行结果如下:


原创粉丝点击