websocket在xhtml+web+android+okHttp中运用实现信息发出去返回来

本文介绍了一个基于XHTML和WebSocket技术实现的简单聊天应用程序。该应用包括客户端和服务器端的实现过程,其中客户端使用了JavaScript进行交互,并通过WebSocket与服务器进行实时通信。此外,还提供了基于Android平台使用OkHttp库实现的WebSocket客户端示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先建立一个xhtml文件,然后代码为:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Apache Tomcat WebSocket Examples: Chat</title>
    <style type="text/css"><![CDATA[
        input#chat {
            width: 410px
        }

        #console-container {
            width: 400px;
        }

        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }

        #console p {
            padding: 0;
            margin: 0;
        }
    ]]></style>
    <script type="application/javascript"><![CDATA[
        "use strict";

        var Chat = {};

        Chat.socket = null;

        Chat.connect = (function(host) {
            if ('WebSocket' in window) {
                Chat.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
                Chat.socket = new MozWebSocket(host);
            } else {
                Console.log('Error: WebSocket is not supported by this browser.');
                return;
            }

            Chat.socket.onopen = function () {
                Console.log('Info: WebSocket connection opened.');
                document.getElementById('chat').onkeydown = function(event) {
                    if (event.keyCode == 13) {
                        Chat.sendMessage();
                    }
                };
            };

            Chat.socket.onclose = function () {
                document.getElementById('chat').onkeydown = null;
                Console.log('Info: WebSocket closed.');
            };

            Chat.socket.onmessage = function (message) {
                Console.log(message.data);
            };
        });

        Chat.initialize = function() {
            if (window.location.protocol == 'http:') {
                Chat.connect('ws://' + window.location.host + '/websocket/chat');
            } else {
                Chat.connect('wss://' + window.location.host + '/websocket/chat');
            }
        };

        Chat.sendMessage = (function() {
            var message = document.getElementById('chat').value;
            if (message != '') {
                Chat.socket.send(message);
                document.getElementById('chat').value = '';
            }
        });

        var Console = {};

        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });

        Chat.initialize();


        document.addEventListener("DOMContentLoaded", function() {
            // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
            var noscripts = document.getElementsByClassName("noscript");
            for (var i = 0; i < noscripts.length; i++) {
                noscripts[i].parentNode.removeChild(noscripts[i]);
            }
        }, false);

    ]]></script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></div>
<div>
    <p>
        <input type="text" placeholder="type and press enter to chat" id="chat" />
    </p>
    <div id="console-container">
        <div id="console"/>
    </div>
</div>
</body>
</html>

然后再src中创建一个包,和一个java类:

package com.cqvie;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value="/chat")
public class Chat {
    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText("�ظ�:"+msg, last);
            }
        } catch (IOException e) {
            try {
                session.close();
            } catch (IOException e1) {  }
        }
    }

    @OnMessage
    public void echoBinaryMessage(Session session, ByteBuffer bb,
            boolean last) {
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendBinary(bb, last);
            }
        } catch (IOException e) {
            try {
                session.close();
            } catch (IOException e1) {  }
        }
    }
}

这样就可以实现输入消息,然后根据发送的消息返回到文本域里面。

android端代码实现websocket发送,采用了okhttp来创建的(okhttp需要先导包,没有的需要先下载):

package com.example.websocket_test;


import okhttp3.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView tv; 
	Button bConnect,bSend;
	OkHttpClient okHttpClient;
	WebSocket ws;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 tv=(TextView)findViewById(R.id.textview1);  
		 bConnect=(Button)findViewById(R.id.button1);
		 bSend=(Button)findViewById(R.id.button2);
		 
		 bConnect.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				 	okHttpClient=new OkHttpClient();  
				 	String ip="10.0.2.2";
			        Request request=new Request.Builder().url("ws://"+ip+":8080/websocket/chat").build();  
			        //�����µ�����
			        ws= okHttpClient.newWebSocket(request,new Listener()); 
			}
		});
		 
		 bSend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				ws.send("Hello!"); //��������
			}
		});
	}
	
	private class Listener extends WebSocketListener{  
        @Override  
        public void onOpen(WebSocket webSocket, Response response) {  
            super.onOpen(webSocket, response);  
        }  
  
        @Override  
        public void onMessage(WebSocket webSocket,final String text) {  
            super.onMessage(webSocket, text);  
            runOnUiThread(new Runnable() {  
                @Override  
                public void run() {  
                    tv.append("\n"+text);  
                }  
            });  
  
        }  
  
        @Override  
        public void onClosed(WebSocket webSocket, int code, String reason) {  
            super.onClosed(webSocket, code, reason);  
        }  
  
        @Override  
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {  
            super.onFailure(webSocket, t, response);  
        }  
    }  

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

### 中职学校网络安全理论课程大纲和教学内容 #### 2025年中职学校网络安全理论课程概述 随着信息技术的发展网络安全已成为信息化社会的重要组成部分。为了适应这一需求,中职学校的网络安全理论课程旨在培养学生具备基本的网络安全意识和技术能力,使学生能够在未来的职业生涯中应对各种网络威胁。 #### 教学目标 该课程的目标是让学生理解网络安全的基本概念、原理和技术手段,掌握常见的安全防护措施,并能应用这些知识解决实际问题。具体来说,学生应达到以下几点: - 掌握计算机网络基础架构及其工作原理; - 理解信息安全管理体系框架及其实现方法; - 学习密码学基础知识以及加密算法的应用场景; - 能够识别常见攻击方式并采取有效防御策略; #### 主要章节安排 ##### 第一章 计算机网络与互联网协议 介绍计算机网络的基础结构和服务模型,重点讲解TCP/IP五层体系结构中的各层次功能特点,特别是传输控制协议(TCP)和用户数据报协议(UDP)[^1]。 ##### 第二章 信息系统安全保障概论 探讨信息系统的脆弱性和风险评估机制,阐述如何通过物理隔离、访问控制等措施来保障系统安全性。 ##### 第三章 密码学入门 讲述对称密钥体制和非对称密钥体制的区别与发展历程,分析公钥基础设施(PKI)的工作流程及其重要性。 ##### 第四章 防火墙技术与入侵检测系统(IDS) 解释防火墙的作用原理及其分类形式(包过滤型、代理服务器型),讨论IDS的功能特性及部署建议。 ##### 第五章 Web应用程序安全 针对Web环境下的特殊挑战展开论述,如SQL注入漏洞利用、跨站脚本(XSS)攻击防范等内容。 ##### 实践环节设置 除了上述理论部分外,在每学期还设有专门实践课时用于模拟真实环境中可能遇到的安全事件处理过程,增强学生的动手操作能力和应急响应水平。 ```python # Python代码示例:简单的MD5哈希函数实现 import hashlib def md5_hash(text): hasher = hashlib.md5() hasher.update(text.encode('utf-8')) return hasher.hexdigest() print(md5_hash("example")) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值