public class CsmConnection extends AppCompatActivity {
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) {
send("Hello, it is me. Mario :)");
System.out.println("new connection opened");
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("closed with exit code " + code + " additional info: " + reason);
}
@Override
public void onMessage(String message) {
System.out.println("received message: " + message);
}
@Override
public void onMessage(ByteBuffer message) {
System.out.println("received ByteBuffer");
}
@Override
public void onError(Exception ex) {
System.err.println("an error occurred:" + ex);
}
}
private Button start;
private TextView output;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_csm_connection);
start = (Button) findViewById(R.id.start);
output = (TextView) findViewById(R.id.output);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WebSocketClient client = null;
try {
client = new EmptyClient(new URI("ws://192.168.2.234:54321"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
client.connect();
client.getConnection();
}
});
}
}
我想接收从服务器获取的数据,服务器的IP地址为ws://192.168.2.234:54321
。我不确定如何从服务器中打印出数据。
我知道我可以连接到服务器。我尝试使用onMessage()
函数,但是我意识到我不会从客户端输入任何内容。
我想从服务器获取消息并显示它。我该怎么做?