html5中可以这样建立连接:
var socket; //实际生产中,id可以从session里面拿用户id var id = Math.random().toString(36).substr(2); if(!window.WebSocket){ window.WebSocket = window.MozWebSocket; } if(window.WebSocket){ socket = new WebSocket("ws://118.89.129.25:1001/xiaoguo/v1/attendance"); socket.onmessage = function(event){ appendln("receive:" + event.data); }; socket.onopen = function(event){ appendln("WebSocket is opened"); login(); }; socket.onclose = function(event){ appendln("WebSocket is closed"); }; }else{ alert("WebSocket is not support"); }
请问可以在java项目中用java语言模拟这个客户端建立连接,且接受数据吗?
网上找的下面的代码只能连接固定host(118.89.129.25),那如何连接ws://118.89.129.25:1001/xiaoguo/v1/attendance 啊?小白求大神指点.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class WebServer { public static final int port = 10010; public static final String host = "118.89.129.25"; public static void main(String[] args) throws IOException{ try{ Socket socket=new Socket(host,1001); System.out.println("client start ..."); //向本机的52000端口发出客户请求 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //由系统标准输入设备构造BufferedReader对象 PrintWriter write=new PrintWriter(socket.getOutputStream()); //由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket对象得到输入流,并构造相应的BufferedReader对象 String readline; readline=br.readLine(); //从系统标准输入读入一字符串 while(!readline.equals("end")){ //若从标准输入读入的字符串为 "end"则停止循环 write.println(readline); //将从系统标准输入读入的字符串输出到Server write.flush(); //刷新输出流,使Server马上收到该字符串 System.out.println("Client:"+readline); //在系统标准输出上打印读入的字符串 System.out.println("Server:"+in.readLine()); //从Server读入一字符串,并打印到标准输出上 readline=br.readLine(); //从系统标准输入读入一字符串 } //继续循环 write.close(); //关闭Socket输出流 in.close(); //关闭Socket输入流 socket.close(); //关闭Socket }catch(Exception e) { System.out.println("can not listen to:"+e);//出错,打印出错信息 } } }