socket俗稱套接字,是Java對於tcp、IP協議的封裝,目的爲了進行網際之間的傳輸信息。
最近公司有個項目,因爲後臺查詢時間太長,需要我以日誌形式將其加載進程輸出到前臺。在網上百度了下,發現了socket。於是便開始研究咯。
什麼socket的三次握手四次分手什麼我看了也不是很懂,我說說我對於他使用的心的,以及後面又選擇websocket和使用這些中遇見的坑。
對於使用socket的使用我就感覺和用微信或者QQ聊天的感覺一樣。在使用socket進行連接時,最主要的兩個類就是serverSocket和socket這兩個類,前者在服務端使用,後者在客戶端使用。我寫了個demo
首先是服務端的代碼
package nc.temptation.test.testSocket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class server {
public static void main(String[] args) {
try {
//開始服務端的服務
ServerSocket serverSocket = new ServerSocket(56990);
//這是爲了建立一個聊天室,但是最後沒有去做,因爲這個對內存佔用太大放棄了
Map<String,String> chatRoom = new HashMap<>();
Socket socket = null;
//監聽客戶端的socket建立
while (true){
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String result = br.readLine();
//輸出客戶端傳來的消息
System.out.println(result);
}
} catch (IOException e) {
//socket會導致一個io口輸出錯誤
e.printStackTrace();
}
}
}
接下來是客戶端的代碼
package nc.temptation.test.testSocket;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket socket = null;
OutputStream os = null;
PrintWriter pw = null;
while (true) {
socket = new Socket("localhost", 56990);
os = socket.getOutputStream();
pw = new PrintWriter(os);
System.out.println("請輸入:");
StringBuffer sb = new StringBuffer();
sb.append("小明說:");
Scanner input = new Scanner(System.in);
String say = sb.append(input.next()).toString();
pw.write(say);
pw.flush();
pw.close();
os.close();
}
}
}
1、在使用socket時一定要端口號和服務器的端口號保持一致,不能使用已經被使用的端口號,這樣的服務是啓動不起來的。
2、先是啓動服務端的服務,監聽客戶端的socket
3、異常一定要捕獲
現在來談談爲什麼最後我放棄了使用它來實現開始說的功能,首先也是最關鍵的我們的項目的客戶端是客戶對我們網頁的訪問,這導致我無法在客戶端運行我的代碼;第二點,socket本質是短連接(我測試過,客戶端在4秒左右不對服務端發送報文,socket會自動斷開),無法自己進行長時間的連接,這樣爲了讓他進行長連接,我就必須讓客戶端定時發送報文給服務端,保證連接不會斷開,這樣在服務端連接數不多時沒有什麼問題,然而當服務端連接數太多時會是個可怕的事情。因此度娘告訴我其實還有個websocket框架啊,你爲甚不用他呢?好唄,我謝謝我娘現在告訴我這個咯。
我就把我寫的代碼貼出來咯。
首先是在controller層的websocketController.java(因爲他和路徑有關係)
package com.voices.duobaoyu.controller;
import com.alibaba.fastjson.JSONObject;
import com.voices.duobaoyu.service.ICompanyService;
import com.voices.duobaoyu.service.IProductService;
import com.voices.duobaoyu.util.IWebsocketResponse;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.lang.reflect.Type;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
public class WebSocketController {
private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<WebSocketController>();
private static int onlineCount = 0;
private Session session;
@Resource
private ICompanyService companyService;
@Resource
private IProductService productService;
public Session getSession() {
return session;
}
/**
* 收到客戶端消息後調用的方法
* @param message 客戶端發送過來的消息
* @param session 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
// message = "{\"api\":\"serializeCompany\",\"param\":\"\"}";
//處理前臺的message
JSONObject msg = JSONObject.parseObject(message);
//api
String api = msg.getString("api");
if(api == null){
//TODO error handling
return;
}
String param = msg.getString("param");
//判斷使用哪個處理函數
if( "serializeCompany".equals(api)){
/**
* @param msg.getstring 編號
* @param session 會話
* @param this hangleMessage回調函數
*/
//公司的序列化處理函數
serializeCompany(param, new IWebsocketResponse() {
@Override
public void send(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
else if ( "serializeProduct".equals(api)) {
//產品的序列化函數
serializeProduct(param, new IWebsocketResponse() {
@Override
public void send(String msg) throws IOException {
session.getBasicRemote().sendText(msg);
}
});
}
}
//向前端發送消息
public void sendMessage(String msg,WebSocketController webSocketController){
try {
webSocketController.getSession().getBasicRemote().sendText(msg+"加載完成");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 連接建立成功調用的方法
* @param session 可選的參數。session爲與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 發生錯誤時調用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("發生錯誤");
error.printStackTrace();
}
//處理公司序列化
public void serializeCompany(String id, IWebsocketResponse response){
//null序列化所有產品,nonull序列化單個產品
Integer param ;
if ("".equals(id)){
// response.send("");
param = null;
}else {
param = Integer.parseInt(id);
}
new Thread(new Runnable() {
@Override
public void run() {
companyService.serializeCompany( param, response);
}
}).start();
}
//處理產品序列化
public void serializeProduct( String id, IWebsocketResponse response){
//null序列化所有產品,nonull序列化單個產品
Integer param ;
if ("".equals(id)){
// response.send("");
param = null;
}else {
param = Integer.parseInt(id);
}
new Thread(new Runnable() {
@Override
public void run() {
productService.serializeProduct( response);
}
}).start();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketController.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketController.onlineCount--;
}
}
util層的(這個藉口的目的是爲了降低controller層與service層的耦合,最開始我使用的類的回調,發現耦合還是很高,我便用藉口在service輸出了)
package com.voices.duobaoyu.util;
import java.io.IOException;
public interface IWebsocketResponse {
void send(String msg) throws IOException;
}
service層代碼
@Override
//序列化公司
public JSONObject serializeCompany(Integer id, IWebsocketResponse response){
JSONObject result = new JSONObject();
result.put("succ", true);
CompanyExample example = new CompanyExample();
CompanyExample.Criteria criteria = example.createCriteria();
if (id != null)
criteria.andIdEqualTo(id);
List<Company> companyList = companyDao.selectByExample(example);
for (Company company : companyList) {
try {
File file = new File("data/companyDetail/" + company.getId() + ".json");
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
JSONObject temp = new JSONObject();
temp.put("succ", true);
temp.put("data", company);
String jsonString = JSONToStringUtil.jsonToString(temp);
writer.write(jsonString);
writer.close();
if (response != null) {
response.send(company.getName());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
result.put("succ", false);
} catch (IOException e) {
e.printStackTrace();
result.put("succ", false);
}
}
try {
response.send("公司序列化完畢");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
最後就是前端代碼了
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2017/9/15
Time: 13:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>序列化公司</title>
<script>
//發送消息
var websocket = null;
console.log(window);
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + location.host + "/duobaoyu_manager/websocket");
}
else {
alert('當前瀏覽器 Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發生錯誤");
};
//連接成功建立的回調方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
if (event.data == "公司序列化完畢"){
alert("公司序列化完畢");
}
}
//連接關閉的回調方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關閉");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function send() {
var message = '{\"api\":\"serializeCompany\",\"param\":\"\"}';
websocket.send(message)
}
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
</script>
</head>
<body>
<a href="javascript:void(0)" onclick="send()">開始序列化</a>
<div id="message"></div>
</body>
</html>
當然前端不只有這些,這個是ifram標籤的內容。
遇到的坑:
1、jaee、spring4.0、Tomcat7.0以後都對他進行了實現,特別是我這個項目開始我用maven加入了這個依賴庫,導致我運行項目運行正常,只是這個功能回出現404的錯誤。
2、在前端第一次握手時,路徑一定要填對,天殺的這個我開始無法理解他路徑,最後理清楚了,就是 URL:ws://Tomcat初始路徑/websocket
3、在ssm中使用它,在他的註釋格式是
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
value的值就是路徑,後面的configurator爲了websocket層可以使用自動裝配,例如:@autowite @Resource。同時要在web.xml中加上這兩個配置
<!--監聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
這兩個配置是爲了監聽web容器的上下文,不添加會報:spring無法尋找到上下文。