Java-WebSocket 项目的研究(二) :客户端连接服务器并发送消息实例

继续之前的教程,我们先下载项目源代码到本地,我们就能看到项目代码的结构如图一所示:


图一


然后,我们在eclipse中新建一个java project,并将java目录下的org目录整个拷进项目的src目录下(这是因为源代码中的包相对路径都是“org.java_websocket”,所以org必须在根目录下)。再将example目录拷进根目录下即可。这个example目录里有几个例子,对我们理解这个项目有很大的作用。


图二是笔者的项目截图:


图二


今天我们讲example中的ChatClient类和ChatServer类。很明显,一下就能开出来这两个类的作用,前者是聊天客户端,后者是聊天服务器。


我们先后右击文件ChatServerChatClient,选择Run As javaApplication即可运行(如图三)。




然后看效果(如图三):




如果出现跟笔者一样的效果,那么恭喜你,你的websocket已经连接服务器成功!


接下来,我们开始发送信息:

先定位到ChatClient的main方法:


  1. public static void main( String[] args ) {  
  2.         WebSocketImpl.DEBUG = true;  
  3.         String location;  
  4.         if( args.length != 0 ) {  
  5.             location = args[ 0 ];  
  6.             System.out.println( "Default server url specified: \'" + location + "\'" );  
  7.         } else {  
  8.             location = "ws://localhost:8887";  
  9.             System.out.println( "Default server url not specified: defaulting to \'" + location + "\'" );  
  10.         }  
  11.         new ChatClient( location );  
  12.     }  
public static void main( String[] args ) {
		WebSocketImpl.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 );
	}

我们分析一下这几句代码。

  1. WebSocketImpl.DEBUG = true;  
		WebSocketImpl.DEBUG = true;

这一句是开启debug模式,不多说了。
  1. location = "ws://localhost:8887";  
			location = "ws://localhost:8887";
这句是服务器地址,下面的
  1. new ChatClient( location );  
		new ChatClient( location );
就是调用了 ChatClient的构造函数。所以下面我们进到其构造函数中看一下,核心代码如下
  1. cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {  
  2.   
  3.                     @Override  
  4.                     public void onMessage( String message ) {  
  5.                         ta.append( "got: " + message + "\n" );  
  6.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  7.                     }  
  8.   
  9.                     @Override  
  10.                     public void onOpen( ServerHandshake handshake ) {  
  11.                         ta.append( "You are connected to ChatServer: " + getURI() + "\n" );  
  12.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  13.                     }  
  14.   
  15.                     @Override  
  16.                     public void onClose( int code, String reason, boolean remote ) {  
  17.                         ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );  
  18.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  19.                         connect.setEnabled( true );  
  20.                         uriField.setEditable( true );  
  21.                         draft.setEditable( true );  
  22.                         close.setEnabled( false );  
  23.                     }  
  24.   
  25.                     @Override  
  26.                     public void onError( Exception ex ) {  
  27.                         ta.append( "Exception occured ...\n" + ex + "\n" );  
  28.                         ta.setCaretPosition( ta.getDocument().getLength() );  
  29.                         ex.printStackTrace();  
  30.                         connect.setEnabled( true );  
  31.                         uriField.setEditable( true );  
  32.                         draft.setEditable( true );  
  33.                         close.setEnabled( false );  
  34.                     }  
  35.                 };  
cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {

					@Override
					public void onMessage( String message ) {
						ta.append( "got: " + message + "\n" );
						ta.setCaretPosition( ta.getDocument().getLength() );
					}

					@Override
					public void onOpen( ServerHandshake handshake ) {
						ta.append( "You are connected to ChatServer: " + getURI() + "\n" );
						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 + "\n" );
						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 ...\n" + ex + "\n" );
						ta.setCaretPosition( ta.getDocument().getLength() );
						ex.printStackTrace();
						connect.setEnabled( true );
						uriField.setEditable( true );
						draft.setEditable( true );
						close.setEnabled( false );
					}
				};



  1. //这句作用是连接服务器    
  2. cc.connect();  
  3. //这句是本人加的,用于发送消息   
  4. cc.send("你好");  
//这句作用是连接服务器 
cc.connect();
//这句是本人加的,用于发送消息
cc.send("你好");


以上的代码作用是先初始化类WebSocketClient然后调用connect,最后发送消息。

完。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Java WebSocket客户示例,用于接收其他客户发送的数据: ```java import java.net.URI; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; public class MyClient extends WebSocketClient { public MyClient(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake handshakedata) { System.out.println("Connected to server!"); } @Override public void onMessage(String message) { System.out.println("Received message: " + message); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("Disconnected from server!"); } @Override public void onError(Exception ex) { System.out.println("Error occurred: " + ex.getMessage()); } } ``` 你可以将上面的代码放在一个类中,然后在主函数中创建一个WebSocket客户实例连接服务器: ```java import java.net.URI; import java.net.URISyntaxException; public class Main { public static void main(String[] args) { try { MyClient client = new MyClient(new URI("wss://example.com")); client.connect(); } catch (URISyntaxException ex) { System.out.println("Invalid server URI!"); } } } ``` 当客户连接服务器后,`onOpen`方法将被调用。在这个方法中,你可以向服务器发送消息或者执行其他初始化操作。当你接收到其他客户发送消息时,`onMessage`方法将被调用。 你可以根据你的需求修改`onMessage`方法来处理接收到的消息。例如,你可以将接收到的消息输出到控制台,或者将它们保存到一个文件中等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值