當前位置:首頁 » 編程語言 » java實現socket長連接

java實現socket長連接

發布時間: 2022-05-27 16:59:00

java Socket 長連接怎麼實現

現編這個就是個多線程伺服器,只要在client不釋放連接,伺服器端的run里邊寫while(TRUE)循環,那麼就可以長期連接。
class ConnectionThread extends Thread{
Socket client;
int counter;
public ConnectionThread(Socket cl,int c){
client = cl;
counter= c;
}
@Override
public void run()
{
try{
String destIP=client.getInetAddress().toString();
int destport =client.getPort();
PrintStream outstream=new PrintStream(client.getOutputStream());
DataInputStream instream=new DataInputStream(client.getInputStream());
String inline=instream.readLine();
}//try
catch(IOException e){System.out.println(e);}
}//run

Ⅱ java怎麼實現長連接

應該是HTTP連接吧,HTTP連接本身的request/response模式設計就是短鏈接的,即伺服器端響應之後斷開連接。
若要做長連接,在沒有具體業務的情況下,最基礎的就是建立java.net.Socket連接,自己制定協議來控制斷開。伺服器端的實現老的有標准IO(java.net.*),新的有NIO(java.nio.*)。有具體業務時可以考慮一些成熟的協議來實現,如XMPP等。

Ⅲ java socket 長連接 客戶端

首先說長連接和短連接
短連接:在獲得tcp連接之後發送數據,然後關閉連接
長連接:獲得tcp連接之後,有數據則發送數據,無數據發送則定時發送數據包,保持連接狀態.

長短只是相對的

你的需求應該在取得socket連接之後建立輸入輸出流,在輸入流得到相應數據之後就可以關閉連接了

Ⅳ java Socket 短連接和長連接的區別

所謂長連接,指在一個TCP連接上可以連續發送多個數據包,在TCP連接保持期間,如果沒有數據包發送,需要雙方發檢測包以維持此連接,一般需要自己做在線維持。
短連接是指通信雙方有數據交互時,就建立一個TCP連接,數據發送完成後,則斷開此TCP連接,一般銀行都使用短連接。
比如http的,只是連接、請求、關閉,過程時間較短,伺服器若是一段時間內沒有收到請求即可關閉連接。
其實長連接是相對於通常的短連接而說的,也就是長時間保持客戶端與服務端的連接狀態。
長連接與短連接的操作過程:
通常的短連接操作步驟是:
連接→數據傳輸→關閉連接;

而長連接通常就是:
連接→數據傳輸→保持連接(心跳)→數據傳輸→保持連接(心跳)→……→關閉連接;
這就要求長連接在沒有數據通信時,定時發送數據包(心跳),以維持連接狀態,短連接在沒有數據傳輸時直接關閉就行了.

Ⅳ 小弟初學java socket,想知道什麼是長連接,什麼是短連接

所謂長連接,就是不管客戶端有沒有數據要發上來,先連接上再說,連接一直保持,數據都從這個連接發送

短連接,就是要發數據的時候才連接,發完數據就將連接斷掉,下次要發數據再重新連接

Ⅵ 請教JAVA如何實現web下的長連接關鍵後台如何寫

目前web上的消息通訊方式主要有以下幾種。
輪詢,長連接,websocket
輪詢:隔一段時間訪問伺服器,伺服器不管有沒有新消息都立刻返回。
長連接:頁面向伺服器發出請求,由伺服器決定什麼時候返回。(如果有新消息則立刻返回,沒有的話就保持連接,直到有新消息才返回)
websocket:類似Java Socket,由Http請求模擬實現的socket。

要實現長連接的關鍵就是: 由伺服器端決定什麼時候返回數據。比如在servlet中。

doGet(...){
...
Thread.sleep(30000);
return ...
}
這就是一個長連接的例子,只是沒有任何意義而已。

你要做的就是在doGet中阻塞住,
while(!hasNewMsg){
sleep(500)
}
return newMsg...

當然你的ajax超時時間要設置長一點。

如果可以的話,最好可以使用websocket。

Ⅶ java 實現長連接接受信息,發送信息

對於你這個需求,可以用當前比較熱門的websocket來解決。

websocket可以實現服務端和客戶端全雙工通信,實時性非常好。

你可以自己搭建websocket服務,也可以使用第三方的websocket推送框架,比如【GoEasy】。

【GoEasy】目前支持java、phppython等服務端語言,同時也支持小程序、vue、uniapp等前端技術,使用起來還是非常方便的。

Ⅷ 如何干凈的實現Android/Java Socket 長連接通信

Java Socket通信有很多的時候需要我們不斷的學習。方面效率雖然不及C與C++但它以靈活語言優勢,為大家廣為使用。 本文就對在使用java做通信方面程序時候應改注意問題做以說明。1.長連接、短鏈接只是針對客戶端而言,伺服器無所謂長、短;2.無論同步或者非同步通信,發送之後務必要又響應回復,確認收到,負責進行一定范圍內重發,例如重發三次;3.長連接伺服器與客戶端之間務必需要心跳探測,由客戶端主動發起;4.短連接伺服器通用代碼:
package com.biesan.sms.gate.unioncom.communication;
import com.biesan.commons.Constants;
import com.biesan.commons.util.CodeUtil;
import com.biesan.sms.gate.unioncom.data.*;
import com.biesan.sms.gate.unioncom.util.GateInfo;
import java.net.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
import spApi.*;
public class UnioncomDeliver extends Thread {
// stop flag
private boolean unInterrupt = true;
private boolean unErr = true;
//private boolean closeSocketFlag = false;
// server socket
private ServerSocket serverSo = null;
// current socket
private Socket so = null
private OutputStream output = null;
private InputStream input = null;
// gate command
private SGIP_Command tmpCmd = null;
private SGIP_Command cmd = null;
private Bind bind = null;
private BindResp bindResp = null;
//private Unbind unBind = null;
private UnbindResp unBindResp = null;
private boolean unAcceptErrorFlag = true;
Logger unioncomLog = Logger.getLogger(Unioncom
Deliver.class.getName());
public UnioncomDeliver() {
}
public void run() {
unioncomLog.info("Start...");
while (unInterrupt) {
this.initServer();
this.startServices();
while (this.unAcceptErrorFlag) {
try {
//接受連接請求
unioncomLog.info("before accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
this.acceptConnection();
unioncomLog.info("after accept connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
while (unErr) {
cmd = new Command();
unioncomLog.info("before read command from stream
........... FreeMemroy: " + Runtime.getRuntime().
freeMemory());
tmpCmd = cmd.read(input);
unioncomLog.info("after read command from stream " +
getCommandString(cmd.getCommandID()) + " FreeMemroy: " +
Runtime.getRuntime().freeMemory());
if (tmpCmd == null) {
unErr = false;
break;
}
switch (cmd.getCommandID()) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
this.dealBind();
break;
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
this.dealUnBind();
unioncomLog.info("after unbind connection!.......
FreeMemroy :" + Runtime.getRuntime().freeMemory());
break;
}// deliver
....
default : //錯誤的命令字
break;
}// switch
}// while(unErr)
} catch (Exception e) {
unioncomLog.error("Unioncom Recv Service Error"
+ e.getMessage());
} finally {
if (this.so != null) {
this.closeSocket();
}
this.unErr = true;
}
}// while (this.unAcceptErrorFlag)
try {
this.closeServerSocket();
sleep(200);// sleep
} catch (InterruptedException ie) {
}
}// while(unInterrupt)
}
private String getCommandString(int cmd){
switch (cmd) {
// biad ready communication
case SGIP_Command.ID_SGIP_BIND: {
return " BIND COMMAND ";
}// exit bind
case SGIP_Command.ID_SGIP_UNBIND: {
return " UNBIND COMMAND ";
}// deliver
case ...
default:
return " UNKNOWN COMMAND";
}
}
private void dealBind() {
try {
bind = new Bind(tmpCmd);
if (bind.readbody() != 0) {
unioncomLog.warn("Read Bind error");
this.unErr = false;
}
bindResp = new BindResp(tmpCmd.getMsgHead());
bindResp.SetResult(0);
bindResp.write(output);
unioncomLog.debug("Bind success!");
} catch (Exception e) {
unioncomLog.error("Dela Union Recv Bind Error!" +
e.getMessage());
this.unErr = false;
}
}
private void dealUnBind() {
try {
//unBind = (Unbind) tmpCmd;
unBindResp = new UnbindResp(tmpCmd.getMsgHead());
unBindResp.write(output);
unioncomLog.debug("UnBind success!");
} catch (Exception e) {
unioncomLog.warn("Unbind error!" + e.getMessage());
}
this.unErr = false;
}
private void startServices() {
boolean unStartServices = true;
while (unStartServices) {
try {
serverSo = new ServerSocket(ugInfo.getLocalServerPort(), 5,
InetAddress.getByName(ugInfo.getLocalIpAdd()));
//serverSo.setSoTimeout(60000);
unStartServices = false;
unioncomLog.info("Create union recv socket Ok!");
} catch (IOException e) {
unioncomLog.warn("Create union recv socket error!"
+ e.getMessage());
unStartServices = true;
UnioncomSubmit.thrSlp(3000);
}
}
}
private void acceptConnection() {
// Accept 失敗
try {
so = serverSo.accept();
so.setSoTimeout(10000);
} catch (Exception e) {
unioncomLog.warn("Accept Error!" + e.getMessage());
this.closeServerSocket();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
// Accept成功
try {
input = so.getInputStream();
output = so.getOutputStream();
} catch (IOException e) {
unioncomLog.warn("Get I/O stream Error!" + e.getMessage());
this.closeService();
this.unAcceptErrorFlag = false;
this.unErr=false;
}
}
private void closeSocket() {
try {
so.close();
unioncomLog.info("Socket Close Success!!!");
} catch (Exception e) {
unioncomLog.error("Socket Close Failure!!!" + e.getMessage());
}
}
private void closeServerSocket() {
try {
serverSo.close();
unioncomLog.info("ServerSocket Close Success!!!");
} catch (Exception e) {
unioncomLog
.error("ServerSocket Close Failure!!!" + e.getMessage());
}
}
private void closeService() {
this.closeSocket();
this.closeServerSocket();
}
private void initServer() {
this.bind = null;
this.bindResp = null;
//this.unBind = null;
this.unBindResp = null;
this.tmpCmd = null;
this.cmd = null;
this.serverSo = null;
this.so = null;
this.output = null;
this.input = null;
this.unErr = true;
//this.closeSocketFlag = false;
unioncomLog.info("Memory***==="
+ java.lang.Runtime.getRuntime().freeMemory());
}
public synchronized void requireStop() {
this.unInterrupt = false;
unioncomLog.info("Requre interrupt!!!");
}
public String convertMsgContentCoding
(int msgCoding, byte[] msgContent) {
String deliverContent = null;
try {
if (msgContent != null) {
if (msgCoding == 8) { // 處理ucs32編碼
deliverContent = new String(msgContent,
"UnicodeBigUnmarked");
} else if (msgCoding == 0) { // 處理ASCII編碼
deliverContent = new String(msgContent, "ASCII");
} else if (msgCoding == 4) { // 處理binary編碼
deliverContent = new String(msgContent);
} else if (msgCoding == 15) { // 處理GBK編碼
deliverContent = new String(msgContent, "GBK");
// 處理DELIVER數據包的簡訊息ID
} else {
unioncomLog.error("編碼格式錯誤!");
return "";
}
} else
return "";
return deliverContent;
} catch (UnsupportedEncodingException ex) {
unioncomLog.error("deal content error!" +
ex.getMessage());
return "";
}
}
}

Ⅸ java socket長連接循環讀取數據

AIO和BIO了解一下

Ⅹ 有個Java 項目,通過Socket Tcp長連接通信方式向伺服器發送消息。

你這消息頭、消息體的結構格式都定下來了,總長度就是固定的啊?消息體的長度不是一共2+2+4+1=9個位元組么?消息格式肯定要按照服務端的要求進行發送,明顯服務端不是java的程序。。但是java里是沒有Unsigned Integer這種數據類型的(java的stream操作里提供了一些unsigned的方法,或者自己寫方法來生成對應的位元組格式),你可以按照他的要求,使用位元組數組封裝好,然後發送。
針對這個示例消息,你可以:
創建一個長度為9的位元組數組。把「9」變成byte放入前兩個位元組(前兩個位元組數據應該為:0x00, 0x09。這是第一個欄位,長度),後面的欄位數據以此類推。一個欄位一個欄位處理成伺服器要求的格式。
然後把位元組流發送給服務端。

熱點內容
android訪問網路許可權 發布:2025-02-12 14:55:20 瀏覽:88
原神文件夾 發布:2025-02-12 14:50:15 瀏覽:800
c語言數字翻譯 發布:2025-02-12 14:45:54 瀏覽:497
暗區突圍為什麼顯示伺服器維修 發布:2025-02-12 14:45:53 瀏覽:247
翻譯分為匯編和編譯 發布:2025-02-12 14:29:12 瀏覽:233
什麼是新聞編譯 發布:2025-02-12 14:23:12 瀏覽:853
如何查看手機存儲 發布:2025-02-12 14:21:15 瀏覽:50
cacti自定義腳本 發布:2025-02-12 14:21:13 瀏覽:313
編譯安卓步驟 發布:2025-02-12 14:19:39 瀏覽:222
php把數組分組 發布:2025-02-12 14:19:37 瀏覽:280