웹소켓의helloworld
12446 단어 websocket
ChatClient.java
ChatServer.java
EmptyClient.java
WebSocket.jar
index.html
index.html
WebSocket Chat Client
document.observe("dom:loaded", function() {
function log(text) {
$("log").innerHTML = (new Date).getTime() + ": " + (!Object.isUndefined(text) && text !== null ? text : "null") +"<br>"+ $("log").innerHTML;
}
if (!window.WebSocket) {
alert("FATAL: WebSocket not natively supported. This demo will not work!");
}
var ws;
$("uriForm").observe("submit", function(e) {
e.stop();
ws = new WebSocket($F("uri"));
ws.onopen = function() {
log("[WebSocket#onopen]");
}
ws.onmessage = function(e) {
log("<b style='color:red;'>[WebSocket#onmessage] :" + e.data + "</b>");
}
ws.onclose = function() {
log("[WebSocket#onclose]");
$("uri", "connect").invoke("enable");
$("disconnect").disable();
ws = null;
}
$("uri", "connect").invoke("disable");
$("disconnect").enable();
});
$("sendForm").observe("submit", function(e) {
e.stop();
if (ws) {
var textField = $("textField");
ws.send(textField.value);
//log("[WebSocket#send] :" + textField.value );
textField.value = "";
textField.focus();
}
});
$("clear").observe("click", function(e) {
$("log").innerHTML ='';
});
$("disconnect").observe("click", function(e) {
e.stop();
if (ws) {
ws.close();
ws = null;
}
});
});
EmptyClient.java
import java.net.URI;
import org.java_websocket.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
public class EmptyClient extends WebSocketClient {
public EmptyClient( URI serverUri , Draft draft ) {
super( serverUri, draft );
}
public EmptyClient( URI serverURI ) {
super( serverURI );
}
@Override
public void onOpen( ServerHandshake handshakedata ) {
}
@Override
public void onMessage( String message ) {
}
@Override
public void onClose( int code, String reason, boolean remote ) {
}
@Override
public void onError( Exception ex ) {
}
}
ChatServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Set;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketServer;
import org.java_websocket.handshake.ClientHandshake;
public class ChatServer extends WebSocketServer {
public ChatServer( int port ) throws UnknownHostException {
super( new InetSocketAddress( InetAddress.getByName( "localhost" ), port ) );
}
public ChatServer( InetSocketAddress address ) {
super( address );
}
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
try {
this.sendToAll( "new" );
} catch ( InterruptedException ex ) {
ex.printStackTrace();
}
System.out.println( conn + " entered the room!" );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
try {
this.sendToAll( conn + " has left the room!" );
} catch ( InterruptedException ex ) {
ex.printStackTrace();
}
System.out.println( conn + " has left the room!" );
}
@Override
public void onMessage( WebSocket conn, String message ) {
try {
this.sendToAll( message );
} catch ( InterruptedException ex ) {
ex.printStackTrace();
}
System.out.println( conn + ": " + message );
}
@Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
}
public void sendToAll( String text ) throws InterruptedException {
Set con = connections();
synchronized ( con ) {
for( WebSocket c : con ) {
c.send( text );
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
public static void main( String[] args ) throws InterruptedException , IOException {
//
WebSocket.DEBUG = true;
int port = 8887;
try {
port = Integer.parseInt( args[ 0 ] );
} catch ( Exception ex ) { }
ChatServer s = new ChatServer( port );
s.start();
System.out.println( "ChatServer started on port: " + s.getPort() );
//
BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) );
while ( true ) {
String in = sysin.readLine();
s.sendToAll( in );
}
}
}
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.handshake.ServerHandshake;
public class ChatClient extends JFrame implements ActionListener {
private static final long serialVersionUID = -6056260699202978657L;
private final JTextField uriField;
private final JButton connect;
private final JButton close;
private final JTextArea ta;
private final JTextField chatField;
private final JComboBox draft;
private WebSocketClient cc;
public ChatClient( String defaultlocation ) {
super( "WebSocket Chat Client" );
Container c = getContentPane();
GridLayout layout = new GridLayout();
layout.setColumns( 1 );
layout.setRows( 6 );
c.setLayout( layout );
Draft[] drafts = { new Draft_17(), new Draft_10(), new Draft_76(), new Draft_75() };
draft = new JComboBox( drafts );
c.add( draft );
uriField = new JTextField();
uriField.setText( defaultlocation );
c.add( uriField );
connect = new JButton( "Connect" );
connect.addActionListener( this );
c.add( connect );
close = new JButton( "Close" );
close.addActionListener( this );
close.setEnabled( false );
c.add( close );
JScrollPane scroll = new JScrollPane();
ta = new JTextArea();
scroll.setViewportView( ta );
c.add( scroll );
chatField = new JTextField();
chatField.setText( "" );
chatField.addActionListener( this );
c.add( chatField );
java.awt.Dimension d = new java.awt.Dimension( 300, 400 );
setPreferredSize( d );
setSize( d );
addWindowListener( new java.awt.event.WindowAdapter() {
@Override
public void windowClosing( WindowEvent e ) {
if( cc != null ) {
cc.close();
}
dispose();
}
} );
setLocationRelativeTo( null );
setVisible( true );
}
public void actionPerformed( ActionEvent e ) {
if( e.getSource() == chatField ) {
if( cc != null ) {
try {
cc.send( chatField.getText() );
chatField.setText( "" );
chatField.requestFocus();
} catch ( InterruptedException ex ) {
ex.printStackTrace();
}
}
} else if( e.getSource() == connect ) {
try {
// cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );
cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {
@Override
public void onMessage( String message ) {
ta.append( "got: " + message + "
" );
ta.setCaretPosition( ta.getDocument().getLength() );
}
@Override
public void onOpen( ServerHandshake handshake ) {
ta.append( "You are connected to ChatServer: " + getURI() + "
" );
ta.setCaretPosition( ta.getDocument().getLength() );
}
@Override
public void onClose( int code, String reason, boolean remote ) {
ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "
" );
ta.setCaretPosition( ta.getDocument().getLength() );
connect.setEnabled( true );
uriField.setEditable( true );
draft.setEditable( true );
close.setEnabled( false );
}
@Override
public void onError( Exception ex ) {
ta.append( "Exception occured ...
" + ex + "
" );
ta.setCaretPosition( ta.getDocument().getLength() );
ex.printStackTrace();
connect.setEnabled( true );
uriField.setEditable( true );
draft.setEditable( true );
close.setEnabled( false );
}
};
close.setEnabled( true );
connect.setEnabled( false );
uriField.setEditable( false );
draft.setEditable( false );
cc.connect();
} catch ( URISyntaxException ex ) {
ta.append( uriField.getText() + " is not a valid WebSocket URI
" );
}
} else if( e.getSource() == close ) {
try {
cc.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
public static void main( String[] args ) {
WebSocket.DEBUG = true;
String location;
if( args.length != 0 ) {
location = args[ 0 ];
System.out.println( "Default server url specified: \'" + location + "\'" );
} else {
location = "ws://localhost:8887";
System.out.println( "Default server url not specified: defaulting to \'" + location + "\'" );
}
new ChatClient( location );
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
iPad에서 WebSocket + Authorization이 연결되지 않음발단은 iPad에서의 개발 환경을 정비하려고 했기 때문이었습니다. VPS에 개발 환경을 넣을 수 있으면 편리하다고 생각해, 를 인스톨 해, 그대로는 누구라도 사용할 수 버리므로, Apache를 리버스 프록시로 해, ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.