Socket实现TCP传输XML st;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.Socket;
import java.UnknownHostException;
public class SocketTest {
private static Logger logger = Logger(SocketTest.class);
public void test(){
String body = getXmlInfo();
logger.info("数据内容:" + body);
//3.发送数据
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader br = null;
try {
//建⽴TCP连接
socket = new Socket("localhost", 8080);
logger.info("创建连接成功");
//写⼊数据
outputStream = OutputStream();
outputStream.Bytes("UTF-8"));
logger.info("发送数据结束");
//获取响应
inputStream = InputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
String info=null;
while((adLine())!=null){
logger.info(info);
}
br.close();
inputStream.close();
outputStream.close();
socket.close();
logger.info("断开连接");
} catch (UnknownHostException e1) {
logger.info("创建连接失败");
} catch (IOException e1) {
logger.info("发送数据失败");
}
}
//⽣成xml格式数据
private String getXmlInfo() {
dom4j读取xmlDocument doc = ateDocument();
Element root = doc.addElement("root");
Element data = root.addElement("data");
Element data = root.addElement("data");
Element meter = data.addElement("name");  meter.setText("test");
return doc.asXML();
}
public static void main(String[] args) {
new SocketTest().test();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。