socket 通信

//创建服务器端ServerSocket
ServerSocket server = new ServerSocket(8888);
socket = server.accept();

//利用dom4j获取xml文件数据
Document doc = DocumentHelper.parseText(receiveStr);//receiveStr接收的字符串
Element root = doc.getRootElement();
for (Iterator i = root.elementIterator(); i.hasNext();) {
   Element login = (Element)i.next();
   String name = login.getName();
   String text = login.getTextTrim()
}

//获取json文件数据
JSONObject object = JSONObject.fromObject(receiveStr);

//创建客服端Socket
Socket socket = new Socket("127.0.0.1",  "8888");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

//利用dom4j组装xml文件数据
Document doc = DocumentHelper.createDocument();
Element root= doc.addElement("login");
Element e = root.addElement("code");
e.addText("0");
//组件jsonObject对象
JSONObject object= new JSONObject();
object.put("code", "0");

//发送数据xml文件
dos.write(doc.asXML().getBytes());
//发送jsonobject对象
dos.write(object.toString());

 

你可能感兴趣的:(socket)