需要注意,由于是从文件读取,而WINDOWS自带的文本文档程序,亲测对于UTF-8文件会不可见地在文件头多出3个字节。另外回车换行也是不可见字节,需要考虑到。
package com.test.common.socket; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * @author Alive */ public class SendTest { private static final int serverport = 20009; public SendTest() { } public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException { SendTest sendTest = new SendTest(); sendTest.sendMsg(); } public void sendMsg() throws IOException, SAXException, ParserConfigurationException { BufferedReader bufferedReader = null; PrintWriter pw = null; //文件输入 InputStream fileInputStream = this.getClass().getResourceAsStream("msg.txt"); BufferedInputStream buff = new BufferedInputStream(fileInputStream); try { InetAddress serveraddr = InetAddress.getLocalHost(); Socket socket = new Socket(serveraddr, 18000); bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(socket.getOutputStream(),true);//true代表即时刷新 System.out.println("buff.available(): "+buff.available()); byte[] data1 = new byte[buff.available()]; buff.read(data1); byte[] data2 = new byte[data1.length-3]; //去掉UTF-8文件中的前三个字节 System.arraycopy(data1, 3, data2, 0, data2.length); //发送 String str = new String(data1,"UTF-8"); pw.write(str.trim()); pw.flush(); System.out.println("send: "+str.trim()); //接收 StringBuilder sb = new StringBuilder(); String recvStr = null; while((recvStr = bufferedReader.readLine())!=null) sb.append(recvStr+" "); System.out.println("recv: "+sb.toString()); socket.close(); } catch (Exception e) { e.printStackTrace(); } } public void show(byte[] bytes) { System.out.print("send: "); for (int i = 0; i < bytes.length; i++) { System.out.print(bytes[i]+" "); } System.out.println(); } }