顺便带个例子:用线程启动的。
public void run() {
URL url;
String c = null;
HttpURLConnection httpConnection = null;
InputStream input = null;
BufferedReader reader = null;
OutputStream out = null;
ObjectOutputStream write = null;
try {
url = new URL(path);
logger.info("创建url服务!url:"+url+" path:"+path);
httpConnection = (HttpURLConnection) url.openConnection();
logger.info("开启http服务!httpConnection :"+httpConnection);
httpConnection.setConnectTimeout(2000);
logger.info("设置超时!");
httpConnection.setDoOutput(true);
logger.info("设置DoOutput !");
httpConnection.setDoInput(true);
logger.info("设置DoInput!");
httpConnection.setUseCaches(true);
logger.info("打开外部工程===" + httpConnection);
out = httpConnection.getOutputStream();
logger.info("获取输出流!out:"+out);
write = new ObjectOutputStream(out);
logger.info("创建Object对象流!out:"+write);
write.writeUTF(massager);
logger.info("写出信息");
write.flush();
logger.info("刷新");
input = (InputStream) httpConnection.getInputStream();
logger.info("获取输入流!input:"+input);
reader = new BufferedReader(new InputStreamReader(input));
logger.info("打开流操作====" + input);
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
c = sb.toString();
logger.info("拿到值后进行转换,转换结果为" + c); } catch (Exception e) {
logger.info("发生异常,异常信息为:" + e.getMessage());
//e.printStackTrace();
c = "2";
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(write != null){
try {
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpConnection != null){
try {
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
logger.info("线程结束");
}
难道拿不到数据包?
我最终的目的是通过WEB端控制另一台PC上的软件。
1.基于tcp协议的socket拿到数据包
2.解析tcp协议,拿到需要的数据(我们当时在协议上费了很大劲)。
3.根据需求,通过javaEE控制层,向页面传输数据或者直接从到数据库(你在这端web服务需要的数据库)。要用到的相关东西:
tcp协议的三次握手(这个是核心,简单但都是以这个为基础建立的)、socket编程(输入输出流,以及解码中文之类的)和web相关知识。难点是数据包的解析。祝你好运。