网页作为客户端与服务器进行socket通信,使用的是socketJS,能成功建立链接但是无法互相发送信息,有人做过这方面的开发吗?能否提供点建议或者弄个最简单的模型看看,急~~
==========================================================================================socketJS介绍
用javascript实现的socket连接
用javascript实现的socket客户端?而且不依赖java apple.
这里有个例子:socketjs.它的巧妙之处是在页面中内嵌入了一个大概300字节的flash,
利用javascript来操纵flash的xmlSocket client,这样就实现了一个伪socket客户端。在flash和javascript结合的越来越紧密的今天,我们已经看到许多这样类似的应用。
我们可以利用这个socketJs来实现一些基于web的即时通讯程序,互动游戏之类的.Demo
http://dev.dschini.org/socketjs/
Souce code
https://thinkforge.org/projects/socketjs/=================================================================================服务端最简化代码:
import java.io.*;
import java.net.*;
public class MyServer{
public static void main(String[] args)
throws IOException{
ServerSocket s=new ServerSocket(6666);
System.out.println("开始:" + s);
try{
Socket socket=s.accept();
try{
System.out.println("连接接受"+socket);
BufferedReader in=new BufferedReader(new InputStreamReader
(socket.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
while(true){
String str=in.readLine();
if(str.equals("q")) break;
System.out.println("对方说:" +str);
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
String input=new String();
input=is.readLine().trim();
out.println(input);
System.out.print("我说:");
out.flush();
}
}
finally{
System.out.println("关闭....");
socket.close();
}
}
finally{
s.close();
}
}
}
==========================================================================================
网页客户端
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<HEAD>
<TITLE>SocketJS: Realtime Javascript Sockets</TITLE>
<meta name="description" content="Sockets in Javascript">
<meta name="author" content="Manfred Weber">
<meta name="keywords" content="realtime,realtimejs,javascript,socket,flash,real,sockets,js,multiuser,dschini">
<style>
.title {
font-face:Verdana,Arial,sans-serif;
font-size:24px;
color:white;
}
.standard {
font-face:Verdana,Arial,sans-serif;
font-size:16px;
color:white;
}
</style>
</HEAD>
<SCRIPT LANGUAGE=JavaScript>
<!--
/*
 * This is just a help function !!!
 */
var nickname;
function connect_user(){
/*
    window.document.socket.SetVariable("data", "PASS xxx");
    window.document.socket.TCallLabel("/", "send" ); 
    window.document.socket.SetVariable("data", "NICK "+nickname);
    window.document.socket.TCallLabel("/", "send" ) 
    document.getElementById("output").value += "\nNICK "+nickname;
    window.document.socket.SetVariable("data", "USER "+nickname+" 0 * : undefined");
    window.document.socket.TCallLabel("/", "send" ) 
    document.getElementById("output").value += "\nUSER "+nickname+" 0 * : undefined";
    window.document.socket.SetVariable("data", "JOIN #findthebug");
    window.document.socket.TCallLabel("/", "send" ) 
    document.getElementById("output").value += "\nJOIN #findthebug";
*/
window.document.socket.SetVariable("data", "NICK "+nickname);
    window.document.socket.TCallLabel("/", "send" ) 
    document.getElementById("output").scrollTop = document.getElementById("output").scrollHeight;
}/*
 * ----------------------------------
 * SocketJS Functions
 * ----------------------------------
 * (c) 2006 by Manfred Weber
 * ----------------------------------
 */
/*
 * SocketOnInit()
 * Event Handler is called when Flash File is loaded
 */
 function SocketOnInit(){};
/*
 * SocketOnData()
 * Event Handler is called when received Data
 */
 function SocketOnData(data){
     document.getElementById("output").value += "\n"+data;
     document.getElementById("output").scrollTop = document.getElementById("output").scrollHeight;
 }
/*
 * SocketOnConnect(success);
 * Event Handler is called when socket is connected
 */
 function SocketOnConnect(success){
     if(success=="true"){
         document.getElementById("output").value += "\n Connection established";
         connect_user();
     } else{
         document.getElementById("output").value += "\n Connection failed";
     }
 }
/*
 * SocketOnClose
 * Event Handler is calles when socket is closed
 */
 function SocketOnClose(){
     document.getElementById("output").value += "\n Connection closed";
 }
/*
 * SocketClose()
 * Close the Socket
 */
 function SocketClose(){
     window.document.socket.TCallLabel("/", "close" );
 }
/*
 * SocketConnect(host,port)
 * Connect to socket. Notice that host must be the same where the .swf file resides!
 */
 function SocketConnect(host,port){
     nickname = document.getElementById("nickname").value;
     window.document.socket.SetVariable("host", host);
     window.document.socket.SetVariable("port", port);
     window.document.socket.TCallLabel("/", "connect" );
 }
/*
 * SocketSend(data)
 * Send data to open socket
 */
 function SocketSend(data){
     window.document.socket.SetVariable("data", data);
     window.document.socket.TCallLabel("/", "send" )
 }
//-----------------------------------------------
//-->
</SCRIPT> 
<BODY bgcolor="#ffffff">
<p><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
 codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"
 width=1 height=1 id="socket">
    <param name=movie value="socket.swf">
    <param name=quality value=high>
    <embed src="socket.swf" quality=high width=1 height=1 type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" name="socket" swLiveConnect="true">
    </embed> 
  </object></p>
<form name="form1" action="#">
<table width="100%"><tr><td align="center">
<table style="border:1px solid black" cellpadding="15" width="500" bgcolor="#8e5275">
<tr><td>
<font face="Verdana,Arial" size="36px" color="white"><b>SocketJS</b></font><br/></td>
</tr>
<tr><td>
<table width="100%" bgcolor="#eeeeee" style="border:1px solid black">
<tr>
  <td width="75%">
    <input type="text" style="width:100%" name="nickname" id="nickname" value="Enter your Nickname!" onClick="this.value='';">  </td>
  <td width="25%">
  <input style="width:100%" type="button" value="Connect" onClick="SocketConnect('localhost',6666);">  </td>
</tr><tr>
  <td height="150" colspan="2">
    <textarea style="width:100%;height:100%;background-color:#ddd" id="output" name="output">Enter Nickname and Connect!
To get a list of commands type:HELPOP USERCMDS</textarea>  </td>
</tr><tr>
  <td width="75%">
    <input type="text" style="width:100%" name="input" id="input" value="HELPOP USERCMDS">  </td>
  <td width="25%">
  <input type="button" style="width:100%" name="send" value="Send" onClick="SocketSend(document.getElementById('input').value);">  </td>
</tr>
</table>
</td></tr>
</table>
</td></tr></table>
</form></BODY>
</HTML>

解决方案 »

  1.   

    如果是FLASH xmlsocket 需要注意以\0结束。而不是传统的\n的方式。BTW,还真有SOCKETJS啊,我还做了一个相同的,起名叫SOCKET4js,呵呵,原理和这个一样。
      

  2.   

    我给你一个修改后的服务器端,你自己看看吧!import java.io.*;
    import java.net.*;public class MyServer {
      public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(6667);
        System.out.println("开始:" + s);
        try {
          Socket socket = s.accept();
          try {
            System.out.println("连接接受" + socket);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            while (true) {
              char b;
              StringBuilder buffer = new StringBuilder();
              while ((b = (char) in.read()) != -1) {
                if (b == 0x0) {
                  // in.read();
                  break;
                }
                buffer.append(b);
              }
              String str = buffer.toString();
              if (str.equals("q"))
                break;
              System.out.println("<<" + str);
              out.print(str);
              out.write(0x0);
              out.println();
              out.flush();
            }
          } finally {
            System.out.println("关闭....");
            socket.close();
          }
        } finally {
          s.close();
        }
      }
    }