java ssm项目 如何在项目启动时 建立一个socket链接。并在项目中可以随时调用

java ssm项目 如何在项目启动时 建立一个socket链接。并在项目中可以随时调用,第1张

你的问题的重点是项目启动时创建socket,只要socket创建成功就能通过tcp或udp协议进行访问了。如何项目启动时创建可以有2种方法:

创建一个继承了ServletContextListener接口的类,在contextInitialized方法里建立socket server端

新建一个Servlet,并设置<load-on-startup>0</load-on-startup>,在service方法里建立socket server端。

下面是一个简单的通讯实例,进行Server和Client之间的文件传输。。如果是简单的文本传输的话简化掉文本操作的内容即可。。

1服务器端

package sterning;

import javaioBufferedInputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFile;

import javaioFileInputStream;

import javanetServerSocket;

import javanetSocket;

public class ServerTest {

int port = 8821;

void start() {

Socket s = null;

try {

ServerSocket ss = new ServerSocket(port);

while (true) {

// 选择进行传输的文件

String filePath = "D:\\librar";

File fi = new File(filePath);

Systemoutprintln("文件长度:" + (int) filength());

// public Socket accept() throws

// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ssaccept();

Systemoutprintln("建立socket链接");

DataInputStream dis = new DataInputStream(new BufferedInputStream(sgetInputStream()));

disreadByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));

DataOutputStream ps = new DataOutputStream(sgetOutputStream());

//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。

pswriteUTF(figetName());

psflush();

pswriteLong((long) filength());

psflush();

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

while (true) {

int read = 0;

if (fis != null) {

read = fisread(buf);

}

if (read == -1) {

break;

}

pswrite(buf, 0, read);

}

psflush();

// 注意关闭socket链接哦,不然客户端会等待server的数据过来,

// 直到socket超时,导致数据不完整。

fisclose();

sclose();

Systemoutprintln("文件传输完成");

}

} catch (Exception e) {

eprintStackTrace();

}

}

public static void main(String arg[]) {

new ServerTest()start();

}

}

2socket的Util辅助类

package sterning;

import javanet;

import javaio;

public class ClientSocket {

private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {

thisip = ip;

thisport = port;

}

/ //

创建socket连接

@throws Exception

exception

/

public void CreateConnection() throws Exception {

try {

socket = new Socket(ip, port);

} catch (Exception e) {

eprintStackTrace();

if (socket != null)

socketclose();

throw e;

} finally {

}

}

public void sendMessage(String sendMessage) throws Exception {

try {

out = new DataOutputStream(socketgetOutputStream());

if (sendMessageequals("Windows")) {

outwriteByte(0x1);

outflush();

return;

}

if (sendMessageequals("Unix")) {

outwriteByte(0x2);

outflush();

return;

}

if (sendMessageequals("Linux")) {

outwriteByte(0x3);

outflush();

} else {

outwriteUTF(sendMessage);

outflush();

}

} catch (Exception e) {

eprintStackTrace();

if (out != null)

outclose();

throw e;

} finally {

}

}

public DataInputStream getMessageStream() throws Exception {

try {

getMessageStream = new DataInputStream(new BufferedInputStream(socketgetInputStream()));

return getMessageStream;

} catch (Exception e) {

eprintStackTrace();

if (getMessageStream != null)

getMessageStreamclose();

throw e;

} finally {

}

}

public void shutDownConnection() {

try {

if (out != null)

outclose();

if (getMessageStream != null)

getMessageStreamclose();

if (socket != null)

socketclose();

} catch (Exception e) {

}

}

}

3客户端

package sterning;

import javaioBufferedOutputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFileOutputStream;

public class ClientTest {

private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {

try {

if (createConnection()) {

sendMessage();

getMessage();

}

} catch (Exception ex) {

exprintStackTrace();

}

}

private boolean createConnection() {

cs = new ClientSocket(ip, port);

try {

csCreateConnection();

Systemoutprint("连接服务器成功!" + "\n");

return true;

} catch (Exception e) {

Systemoutprint("连接服务器失败!" + "\n");

return false;

}

}

private void sendMessage() {

if (cs == null)

return;

try {

cssendMessage(sendMessage);

} catch (Exception e) {

Systemoutprint("发送消息失败!" + "\n");

}

}

private void getMessage() {

if (cs == null)

return;

DataInputStream inputStream = null;

try {

inputStream = csgetMessageStream();

} catch (Exception e) {

Systemoutprint("接收消息缓存错误\n");

return;

}

try {

//本地保存路径,文件名会自动从服务器端继承而来。

String savePath = "E:\\";

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

int passedlen = 0;

long len=0;

savePath += inputStreamreadUTF();

DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));

len = inputStreamreadLong();

Systemoutprintln("文件的长度为:" + len + "\n");

Systemoutprintln("开始接收文件!" + "\n");

while (true) {

int read = 0;

if (inputStream != null) {

read = inputStreamread(buf);

}

passedlen += read;

if (read == -1) {

break;

}

//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比

Systemoutprintln("文件接收了" + (passedlen 100/ len) + "%\n");

fileOutwrite(buf, 0, read);

}

Systemoutprintln("接收完成,文件存为" + savePath + "\n");

fileOutclose();

} catch (Exception e) {

Systemoutprintln("接收消息错误" + "\n");

return;

}

}

public static void main(String arg[]) {

new ClientTest();

}

}

服务端监听:ServerSocket

server=new

ServerSocket(port);//port:绑定的端口号

Socket

client=serveraccept();//监听端口,一旦取得连接则获得客户端的socket连接对象client

客户端:

Socket

s=new

Socket(ip,port);//要连接的服务器的ip以及端口号

如果正常连接上之后,socket的对象可以获得InputStream和OutputStreame,然后就可以进行通信了

完成通信之后,执行socket对象的close()方法关闭连接,完成一次完整的socket连接

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » java ssm项目 如何在项目启动时 建立一个socket链接。并在项目中可以随时调用

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情