java发送socket信息

package org.leo.boss.socket;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import org.springframework.stereotype.Service;
import common.Logger;

@Service
public class SocketUtil {
	private static Logger log = Logger.getLogger(SocketUtil.class);
	
	private Socket socket;
	private OutputStream out;
	private InputStream in;
	
	public String sendSocketMsg(String ip, int port, String msg) {
		byte[] dataBytes = msg.getBytes();
		try {
			socket = new Socket(ip, port);
			socket.setSoTimeout(60 * 1000);
			out = socket.getOutputStream();
			in = socket.getInputStream();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteBuf byteBuf = Unpooled.buffer(2 + dataBytes.length);
		byteBuf.writeChar(dataBytes.length);
		byteBuf.writeBytes(dataBytes);
		try {
			out.write(byteBuf.array());
			byte[] b = new byte[2048];
			// 获取输入流
			in.read(b);
			byte[] len = Arrays.copyOfRange(b, 0, 2);
			int lenth = byteArrayToInt(len);
			byte[] dataRe = Arrays.copyOfRange(b, 2, lenth + 2);
			close();
			return new String(dataRe);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static int byteArrayToInt(byte[] b) {
		return b[1] & 0xFF | (b[0] & 0xFF) << 8;
	}
	
	public void close() throws IOException {
		if (socket != null)
			socket.close();
	}
}

你可能感兴趣的:(JAVA)