Socket简单的数据包的发送与接收
具体的发包与拆包的协议可以自己定义:
我定义:包头第一个字节为1时则为接收文件为0则为接收字符
服务器:
private static void writefile(DataOutputStream dos, FileInputStream fis) {
byte[] bytes=new byte[2];//先发包头
int length;
bytes[0]=1;
bytes[1]=5;
try {
doswrite(bytes);//发给客户端
} catch (IOException e) {
eprintStackTrace();
Systemoutprintln("发送包头失败");
}
try{
byte[] bytes1=new byte[1024];//发送包体数据
while((length=fisread(bytes1, 0,bytes1length))!=-1){
doswrite(bytes1,0,bytes1length);
dosflush();
}
}catch(Exception e){
eprintStackTrace();
Systemoutprintln("发送文件包体数据失败");
}
}
private static void writestring(DataOutputStream dos) {
// TODO Auto-generated method stub
String string="sending";
byte[] bytes=new byte[2];//同理发送字符串的包头
bytes[0]=0;
bytes[1]=5;
try {
doswrite(bytes);
} catch (IOException e) {
eprintStackTrace();
Systemoutprintln("发送包头失败");
}
try {
byte[] bytes1=new byte[1024];//发送字符串的包体数据
bytes1=stringgetBytes();
doswrite(bytes1);
} catch (IOException e1) {
e1printStackTrace();
Systemoutprintln("发送字符包体数据失败");
}
}
}
客户端:
try{
s=new Socket("1921681106",45);
Logd(TAG, "run:2222222222222");
is=sgetInputStream();
dis=new DataInputStream(is);
new Thread(){
@Override
public void run(){
superrun();
try{
dis = new DataInputStream(sgetInputStream());
Logd(TAG, "33333333333333");
byte[] bytes=new byte[2];
disread(bytes);
if(bytes[0]==0){
int a=bytes[1];
byte[] bytes1=new byte[a];
disreadFully(bytes1);
String ssss=new String(bytes1);
Message msg=new Message();
msgwhat=2;
msgobj=ssss;
revhandlersendMessage(msg);
}
else {
{
File file=new File("/storage/emulated/0/1/cjpg");
Logd(TAG,"run:255555555555555555555555");
fos=new FileOutputStream(file);
Logd(TAG,"run:333333333333333333333");
inputByte = new byte[30];//接收数据
Message msg=new Message();
msgwhat=0;
revhandlersendMessage(msg);
Logd(TAG,"run:44444444444444");
while((length = disread(inputByte, 0, inputBytelength)) != -1) {
Logd(TAG,"44444444");
foswrite(inputByte,0,inputBytelength);
fosflush();
}
msg = new Message();
msgwhat=1;
revhandlersendMessage(msg);
if(fos != null)
fosclose();
if(dis != null)
disclose();
sclose();
}
}
} catch (FileNotFoundException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
}
}start();
} catch (UnknownHostException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
运行结果:
服务器:
![V1LEZDB Z07VQ482$02HO%Rpng
客户端:
以下是android手机上发送文件名并且得到文件大小的代码Java
code
//
向服务器提出下载请求,返回下载文件的大小
private
long
request(String
fileName,
String
password)
throws
IOException
{
//
获取socket的输入流并包装成DataInputStream
DataInputStream
in
=
new
DataInputStream(socketgetInputStream());
//
获取socket的输出流并包装成PrintWriter
PrintWriter
out
=
new
PrintWriter(new
OutputStreamWriter(
socketgetOutputStream()));
//
生成下载请求字符串
String
requestString
=
fileName;//
+
@
+
password;
Systemoutprintln(发出下载请求:+fileName);
outprintln(requestString);
//
发出下载请求
outflush();
return
inreadLong();
//
接收并返回下载文件长度}
以下是C#服务器收到android发来的文件名,知道文件之后发送文件大小和文件的代码C#
code
private
string
ReceiveFileName(){string
recvStr
=
;byte[]
recvBytes
=
new
byte[1024];int
bytes
=
m_socketReceive(recvBytes,
recvBytesLength,
0);
//从android客户端接受信息recvStr
=
EncodingASCIIGetString(recvBytes,
0,
bytes);ConsoleWriteLine(文件名+recvStr);return
recvStr;//返回文件名}
private
void
SendFile(){while
(m_IsStart){string
fileName
=
ReceiveFileName();if
(fileName
!=
){if
(FileExists(m_FileDirect
+
1jpg))//下载本地存在的一个文件{FileInfo
fi
=
new
FileInfo(m_FileDirect
+
1jpg);byte[]
len
=
BitConverterGetBytes(fiLength);m_socketSend(len);//发送文件的长度//发送文件try{m_socketSendFile(m_FileDirect
+
1jpg);}catch
(Exception
e){ConsoleWriteLine(出现错误
+
eMessage);}}}}}
------解决方案--------------------------------------------------------
Java
code//
获取socket的输入流并包装成DataInputStream
这个不就是接收的地方吗在第一段代码中
可以定义一个结构体变量,结构体里面有float、double类型的数据,然后发送;
参考如下:
struct person{
char name[20];
int age;
float high;
};
/可在发送数据的地方对数据进行处理,将其转换成一个字符串进行传送,而在接受方定义相同的结构体对这个字符串进行解析即可。/
//发送方代码如下:
char temp[100]; //传送的字符串
struct person p1; //声明一个需要传送的结构体
p1age = 10;
p1high = 180f;
strcpy(p1name,"zhangsan",sizeof(p1name));
memset(temp,0,sizeof(temp)); //对该内存段进行清 0
memcpy(temp,&p1,sizeof(person)); //把这个结构体中的信息从内存中读入到字符串temp中
//接下来传送temp这个字符串就可以了
sendto(sock,temp,sizeof(person),0,(SOCKADDR)&addSer,sizeof(SOCKADDR));
//这样这个结构体的信息就发送到addSer相应的套接字了
/接收方代码如下:
同样需要定义字符串和相同的结构体对象/
char temp[100]; //传送的字符串
struct person p2; //声明一个存放接收信息的结构体
memset(temp,0,sizeof(temp)); //清内存
//下面是接收字符串的代码
recvfrom(sock_listen,temp,sizeof(temp),0,(sockaddr)&addCli,&len);
//下面对字符串信息进行还原,将其变成的结构体数据
memcpy(&p2,temp,sizeof(person)); //解析过程
//下面就可以对p2中的数据进行各种操作了,也完成了结构体数据的传送。
你的文件中的问题
// 会阻塞进程,直到有客户端连接上来为止
// 既然是直到有客户端连接上,那么就要弄明白哪个是与客户端连接的套接字
// sockClient就是与客户端连接的套接字
sockClient = accept(sockServer, (SOCKADDR)&addrClient, &len);
//接收并打印客户端数据
recv(sockClient, recvBuf, 100, 0);
printf("%s\n", recvBuf);
// 所以此处,应该把sockServer改为sockClient
send(/sockServer/sockClient, sendBuf, 100, 0);
PS:服务器客户端通信,是要保持服务器与客户端的连接。
而不能这样立即关闭,如果设置不对,立即关闭,缓冲区的数据是会丢失的。那客户端也就不会再收到数据了。
你可以加Sleep(10000);来测是通信过程
//关闭socket
closesocket(sockClient);
下面是一个简单的通讯实例,进行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();
}
}
0条评论