java实现socket长连接
Ⅰ 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、php、python等服务端语言,同时也支持小程序、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。这是第一个字段,长度),后面的字段数据以此类推。一个字段一个字段处理成服务器要求的格式。
然后把字节流发送给服务端。