通过Socket进行读,写操作(以下代码可以直接负责使用)
public class SocketUtil {
private static String line;
Socket socket = null;
String ip = "192.168.10.107";
int port = 6000;
public SocketUtil() {
if (socket == null) {
try {
socket = new Socket(ip, port);
//设置10秒之后即认为是超时
socket.setSoTimeout(10000);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读数据
*
* @return
*/
public String readData() {
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br;
try {
//读取数据
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
line = br.readLine();
System.out.println("接收到的数据为---->:" + line);
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return line;
}
/**
* 写数据
*
* @param str1
* @param str2
* @return
*/
public String writeData(final String str1, final String str2) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//发送数据给服务端
OutputStream outputStream = socket.getOutputStream();
outputStream.write(str1.getBytes("UTF-8"));
outputStream.write(str2.getBytes("UTF-8"));
socket.shutdownOutput();
//读取数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
System.out.println("接收到的数据为---->:" + line);
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return line;
}
}