} catch(IOException e) { System.out.println("Couldn't get I/O for the connection!"); System.out.println( e.getMessage() ); } } }以上程序都可以正常执行但当浏览器提交时候,ClientMsg不能正常得到数据,按说应该得到 GET /login?name=NAME&passwd=PWD HTTP/1.1 为什么得不到了,是哪里的问题?
此程序只作为调试之用// Server.javaimport java.io.*; import java.net.*; import java.util.*;public class Server { // The ServerSocket we'll use for accepting new connections private ServerSocket ss; // A mapping from sockets to DataOutputStreams. This will // help us avoid having to create a DataOutputStream each time // we want to write to a stream. private Hashtable outputStreams = new Hashtable(); // Constructor and while-accept loop all in one. public Server( int port ) throws IOException { // All we have to do is listen listen( port ); } private void listen( int port ) throws IOException { // Create the ServerSocket ss = new ServerSocket( port ); // Tell the world we're ready to go System.out.println( "Listening on "+ss ); // Keep accepting connections forever while (true) { // Grab the next incoming connection Socket s = ss.accept(); // Tell the world we've got it System.out.println( "Connection from "+s ); // Create a DataOutputStream for writing data to the // other side DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again outputStreams.put( s, dout ); // Create a new thread for this connection, and then forget // about it new ServerThread( this, s ); } } // Get an enumeration of all the OutputStreams, one for each client // connected to us Enumeration getOutputStreams() { return outputStreams.elements(); } // Send a message to all clients (utility routine) void sendToAll( String message ) { // We synchronize on this because another thread might be // calling removeConnection() and this would screw us up // as we tried to walk through the list synchronized( outputStreams ) { // For each client ... for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) { // ... get the output stream ... DataOutputStream dout = (DataOutputStream)e.nextElement(); // ... and send the message try { //dout.writeUTF( message ); dout.writeChars(message); } catch( IOException ie ) { System.out.println( ie ); } } } } // Remove a socket, and it's corresponding output stream, from our // list. This is usually called by a connection thread that has // discovered that the connectin to the client is dead. void removeConnection( Socket s ) { // Synchronize so we don't mess up sendToAll() while it walks // down the list of all output streamsa synchronized( outputStreams ) { // Tell the world System.out.println( "Removing connection to "+s ); // Remove it from our hashtable/list outputStreams.remove( s ); // Make sure it's closed try { s.close(); } catch( IOException ie ) { System.out.println( "Error closing "+s ); } } } // Main routine // Usage: java Server <port> static public void main( String args[] ) throws Exception { // Get the port # from the command line int port = 1800; // Create a Server object, which will automatically begin // accepting connections. new Server( port ); } }// ServerThread.java import java.io.*; import java.net.*;public class ServerThread extends Thread { // The Server that spawned us private Server server; // The Socket connected to our client private Socket socket; // Constructor. public ServerThread( Server server, Socket socket ) { // Save the parameters this.server = server; this.socket = socket; // Start up the thread start(); } // This runs in a separate thread when start() is called in the // constructor. public void run() { try { // Create a DataInputStream for communication; the client // is using a DataOutputStream to write to us //DataInputStream din = new DataInputStream( socket.getInputStream() ); //System.out.println(din.readUTF()); // ... PrintStream dout = new PrintStream( socket.getOutputStream() ); DataInputStream din = new DataInputStream( socket.getInputStream() ); // dout.writeUTF("connection successfully!"); dout.println("HTTP/1.0 200 OK"); dout.println("Date: Fri, 31 Dec 1999 23:59:59 GMT"); dout.println("Content-Type: text/html"); //dout.println("Content-Length: 54"); dout.println("<html>"); dout.println("hello"); dout.println("</html>"); //dout.flush(); while (true) { // ... read the next message ... String message = din.readLine();
// ... tell the world ... System.out.println( "Sending "+message );
// ... and have the server send it to all clients server.sendToAll( message ); } } catch( EOFException ie ) { // This doesn't need an error message } catch( IOException ie ) { // This does; tell the world! System.out.println(ie.getMessage()); } finally { // The connection is closed for one reason or another, // so have the server dealing with it server.removeConnection( socket ); } } }
但是如果使用他的话,也就不能达到push的作用了
我建议你到网上去搜索一下
有许多简单的服务器例子你可以去看一看
http://127.0.0.1:1800/login?name=NAME&passwd=PWD 此时会产生了一个连接到服务器聊天端口的Socket联接,并发送了一行数据:
GET /login?name=NAME&passwd=PWD HTTP/1.1我写了个ClientTest响应键盘并将System.in发送到端口,由Server处理发送到各个Client端口import java.io.*;
import java.net.*;public class ClientTest
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("211.69.137.165", 1800);
DataOutputStream out = new DataOutputStream( s.getOutputStream() );
DataInputStream in = new DataInputStream( s.getInputStream() );
DataInputStream stdIn = new DataInputStream(System.in);
String userInput;
while(true)
{
userInput = stdIn.readLine();
out.writeUTF(userInput);
}
}
catch(IOException e)
{
System.out.println("Couldn't get I/O for the connection!");
System.out.println( e.getMessage() );
}
}
}
ClientMsg.java 得到服务器发出的信息//$id:ClientMsg.java
import java.io.*;
import java.net.*;public class ClientMsg
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("211.69.137.165", 1800);
DataInputStream in = new DataInputStream( s.getInputStream() );
while(true)
{
System.out.println( "Message: " + in.readUTF() );
}
}
catch(IOException e)
{
System.out.println("Couldn't get I/O for the connection!");
System.out.println( e.getMessage() );
}
}
}以上程序都可以正常执行但当浏览器提交时候,ClientMsg不能正常得到数据,按说应该得到
GET /login?name=NAME&passwd=PWD HTTP/1.1
为什么得不到了,是哪里的问题?
建议你用软件截取http request和response,好好分析结构。securitymanager在这里没关系,在rmi和servlet时用,socket不需要。
好,我来试试,谢谢
如
URL url=new URL("http://1`27.0.0.1:8000");
URLConnection conn=new URLConnection(url);
conn.get**Stream()
另外"\r\n"最好写为'\u0d0a',因为java中却省将一个字符作为16位而不是8位
不过可以做“ISO-8859-1”等编码改变
http协议是无状态协议,即只有客户端向服务器端发出请求(包括get put head 等等action),服务器根据请求的内容作出响应。无法做到服务器主动向浏览器推送数据。所谓的“推”技术一般都是基于socket的applet或者刷新(巧妙的无非是局部刷新)。通过url提交的信息浏览器也无法接受到---服务器向浏览器提交?显然不可能咯,呵呵。
所以,根据http协议来看,浏览器不向服务器发出请求,服务器根本不知道你的存在,或者说不care,如何能推,如何能实时呢?如果你的意思是要通过浏览器访问服务器的8000,那用URLConnection就好了,只要构造一个合适的url,在url里面带上必需的参数即可。
不过更好的方法是在服务器端运行一个servlet,通过他去连接你的聊天室服务器。这样的话,webchat通过和servlet交互即可。不过不好的地方是这不是实时聊天。
实时聊天,也就所谓的“推”,最好的方法是做一个applet来做client
通讯协议也就不一定要用http协议来包装了(用http协议的好处是一般的防火墙不限制)。
如果用applet还可以通过javascript发出浏览请求,也很方便。
谢谢,问题是出在readUTF()中,我换成了readLine()正常
谢谢你的帮助。 问题出现是在于使用了readUTF(), 应该使用readLine(); 另外使用PrintStream代替DataOutputStream(); 经过修改以上程序调试后正常,java可以模仿http协议,也可以得到http传送的数据。做server push其实也很简单,只要不设置Content-Length就可以了。 调试程序见下
import java.net.*;
import java.util.*;public class Server
{
// The ServerSocket we'll use for accepting new connections
private ServerSocket ss; // A mapping from sockets to DataOutputStreams. This will
// help us avoid having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable outputStreams = new Hashtable(); // Constructor and while-accept loop all in one.
public Server( int port ) throws IOException { // All we have to do is listen
listen( port );
} private void listen( int port ) throws IOException { // Create the ServerSocket
ss = new ServerSocket( port ); // Tell the world we're ready to go
System.out.println( "Listening on "+ss ); // Keep accepting connections forever
while (true) { // Grab the next incoming connection
Socket s = ss.accept(); // Tell the world we've got it
System.out.println( "Connection from "+s ); // Create a DataOutputStream for writing data to the
// other side
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout ); // Create a new thread for this connection, and then forget
// about it
new ServerThread( this, s );
}
} // Get an enumeration of all the OutputStreams, one for each client
// connected to us
Enumeration getOutputStreams() {
return outputStreams.elements();
} // Send a message to all clients (utility routine)
void sendToAll( String message ) { // We synchronize on this because another thread might be
// calling removeConnection() and this would screw us up
// as we tried to walk through the list
synchronized( outputStreams ) { // For each client ...
for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) { // ... get the output stream ...
DataOutputStream dout = (DataOutputStream)e.nextElement(); // ... and send the message
try {
//dout.writeUTF( message );
dout.writeChars(message);
} catch( IOException ie ) { System.out.println( ie ); }
}
}
} // Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connectin to the client is dead.
void removeConnection( Socket s ) { // Synchronize so we don't mess up sendToAll() while it walks
// down the list of all output streamsa
synchronized( outputStreams ) { // Tell the world
System.out.println( "Removing connection to "+s ); // Remove it from our hashtable/list
outputStreams.remove( s ); // Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing "+s );
}
}
} // Main routine
// Usage: java Server <port>
static public void main( String args[] ) throws Exception { // Get the port # from the command line
int port = 1800; // Create a Server object, which will automatically begin
// accepting connections.
new Server( port );
}
}// ServerThread.java
import java.io.*;
import java.net.*;public class ServerThread extends Thread
{
// The Server that spawned us
private Server server; // The Socket connected to our client
private Socket socket; // Constructor.
public ServerThread( Server server, Socket socket ) { // Save the parameters
this.server = server;
this.socket = socket; // Start up the thread
start();
} // This runs in a separate thread when start() is called in the
// constructor.
public void run() { try { // Create a DataInputStream for communication; the client
// is using a DataOutputStream to write to us
//DataInputStream din = new DataInputStream( socket.getInputStream() );
//System.out.println(din.readUTF());
// ...
PrintStream dout = new PrintStream( socket.getOutputStream() );
DataInputStream din = new DataInputStream( socket.getInputStream() );
// dout.writeUTF("connection successfully!");
dout.println("HTTP/1.0 200 OK");
dout.println("Date: Fri, 31 Dec 1999 23:59:59 GMT");
dout.println("Content-Type: text/html");
//dout.println("Content-Length: 54");
dout.println("<html>");
dout.println("hello");
dout.println("</html>");
//dout.flush();
while (true) { // ... read the next message ...
String message = din.readLine();
// ... tell the world ...
System.out.println( "Sending "+message );
// ... and have the server send it to all clients
server.sendToAll( message );
}
} catch( EOFException ie ) { // This doesn't need an error message
} catch( IOException ie ) { // This does; tell the world!
System.out.println(ie.getMessage());
} finally { // The connection is closed for one reason or another,
// so have the server dealing with it
server.removeConnection( socket );
}
}
}