下面是一个简单的通讯实例,进行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();
}
}
方法如下:
新建eclipse工程,添加commjar或者RXTXcommjar包。因为javacomm20-win32zip包里有样例SimpleReadjava,可以通过这个例子测试串口是否正确。
接收数据正确后,根据传送接收双方的协议,采用CRC循环校验,根据传输的一方的校验函数判定是否是正确传输。
把正确结束的数据解析,查看自己指定的通讯规则,然后解析。
插入数据库,jdbc插入。
数据统计,定时统计每小时,每天,每月,每年的平均值,采用quartz服务来实现。
建立web工程,采用hibernate3,spring3,dwr技术把数据库数据动态显示,图表采用jfreechart,以及AJAX的运用
java优点:
java是纯面向对象编程的语言;
平台无关性 (一次编译,到处运行;Write Once,Run Anywhere);
java提供了许多内置的类库,通过这些类库,简化了开发人员的设计工作,同时缩短了项目开发时间;
提供了对Web应用开发的支持,例如,Applet,Servlet,和JSP可以用来开发Web应用程序,,Socket,RMI可以用来开发分布式应用程序的类库;
去除了c++中难以理解,容易混淆的特性(如c++中的多继承,头文件,指针,结构,单元,运算符重载,虚拟基础类,使得程序更加严谨,整洁。
发送消息之前转码为16进制
Java code
public static final String encodeHex(String msg) {
byte[] bytes = null;
try {
bytes = msggetBytes("GBK");
} catch (javaioUnsupportedEncodingException e) {
eprintStackTrace();
}
StringBuffer buff = new StringBuffer(byteslength 4);
String b;
char a;
int n = 0;
int m = 0;
for (int i = 0; i < byteslength; i++) {
b = IntegertoHexString(bytes[i]);
if (bytes[i] > 0) {
buffappend("00");
buffappend(b);
n = n + 1;
} else {
a = msgcharAt((i - n) / 2 + n);
m = a;
b = IntegertoHexString(m);
buffappend(bsubstring(0, 4));
i = i + 1;
}
}
return bufftoString();
}
以上就是关于用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的全部的内容,包括:用Java socket 实现客户端与服务器之间的数据的发送与接受。。。双向的、在java的web程序中怎么使用串口通讯、java的socket通信如何直接接收16进制数据等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)