package com.jm.jmsdk_tools_jar;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class Socketest {
public synchronized static String sendMsg(String host, int port, String msg) {
// 写
String result = null;
InputStream is = null;
OutputStreamWriter osw = null;
BufferedReader reader = null;
Socket socket = new Socket();
try {
if (port < 0) {
return "";
}
InetSocketAddress isa = new InetSocketAddress(host, port);
socket.connect(isa, 10000);
osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter writer = new BufferedWriter(osw);
writer.write(msg);
writer.flush();
byte[] a = readStream(socket.getInputStream());
result = new String(a);
System.out.println("result:" + result);
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (ConnectException e) {
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (reader != null)
try {
reader.close();
} catch (Exception e) {
}
closeOutputStreamWriter(osw);
closeInputStream(is);
closeSocket(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
private static void closeOutputStreamWriter(OutputStreamWriter osw) throws IOException {
if (osw != null) {
osw.close();
}
}
private static void closeInputStream(InputStream is) throws IOException {
if (is != null) {
is.close();
}
}
private static void closeSocket(Socket socket) throws IOException {
if (socket != null) {
socket.close();
}
}
private static byte[] readStream(InputStream inputStream) throws IOException {
int count = 0;
while (count == 0) {
count = inputStream.available();
}
byte[] b = new byte[count];
inputStream.read(b);
return b;
}
}