本节来说说网络数据的传输。在网络信道中,所有数据都只能按字节传输。这好比,一栋大楼,先拆成一块块砖头,然后再组合成一栋高楼。拆成砖头的过程,我们可以称之为编码,组成大楼的过程我可以称之为解码。
首先我们从最简单文本传输开始说,在文本的传输时,我们也要将字符串编码和解码;
编码:
String -->byte[]
String msg = "Hello";
byte[] data = msg.getBytes("UTF-8"); // GBK
解码:
byte[] --> String
byte[] data = new byte[4000]; // 准备一个大点的缓冲区
int n = inputStream.read( data ); // 实际收到了N字节
String msg = new String(data, 0, n, "UTF-8"); // 前N字节转成字符串
值得注意的是,一个中文字符要占多少个字节,可能是2个也可能是3个,因为不同编码格式占的字节时不同的。如果是GBK编码,则占2个字节,如果是UTF-8则是占2~3个字节。所以在数据传输的时候,也要规定好编码格式,否则就会出现乱码情况。比如,用GBK格式编码,然后用UTF-8的格式解码,此时就会出现乱码。
到此,我们学会了文本的数据的传输。下面思考有个问题,那么对象应该如何传输呢。上面我们提到了文本传输,我们可以将对象转成文本然后编码对其进行传输。于是,有一个方案,首先将对象转成json格式的对象,接着将json对象转成文本,然后对文件进行编码,解码则是逆向过程。举一个例子,有一个Student对象包含以下信息:
public class Student { public int id; public String name; public boolean sex; public String cellphone; }
下面我们对这些信息进行传输。这个例子需要导入一个第三方jar来处理json格式的数据:json-org-build20180908.jar
Student类
package my;
public class Student
{
private int id;
private String name;
private boolean sex;
private String cellPhone;
public Student()
{
super();
}
public Student(int id, String name, boolean sex, String cellPhone)
{
super();
this.id = id;
this.name = name;
this.sex = sex;
this.cellPhone = cellPhone;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSex()
{
return sex;
}
public void setSex(boolean sex)
{
this.sex = sex;
}
public String getCellPhone()
{
return cellPhone;
}
public void setCellPhone(String cellPhone)
{
this.cellPhone = cellPhone;
}
@Override
public String toString()
{
// TODO Auto-generated method stub
return "学号:" + this.id + "\r\n" + "姓名:" + this.name + "\r\n性别:" + this.sex + "\r\n手机号码:" + this.cellPhone + "\r\n";
}
}
1、首先是服端的代码
package my;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.json.JSONObject;
public class MyServer
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//建立服务器,服务于2019端口
ServerSocket serverSock = new ServerSocket(2019);
System.out.println("服务器启动,等待连接...");
while(true)
{
//监听请求,阻塞等待,直到有客户端发起连接...
Socket conn = serverSock.accept();
//从连接里得到输入输出流
//InputStream:可以读取客户端发来的数据
//OutputStream:可以发送数据给客户端
InputStream inputStream = conn.getInputStream();
OutputStream outputStream = conn.getOutputStream();
//接收数据
byte[] inputData = new byte[4000];
int n = inputStream.read(inputData);
if(n <= 0)
{
conn.close();
continue;
}
//发送数据
String inputMsg = new String(inputData , 0 , n , "UTF-8");
System.out.println("GOT:" + inputMsg);
//将接受到的数据转换为学生对象
JSONObject obj = new JSONObject(inputMsg);
Student stu = new Student();
stu.setId(obj.optInt("id" , 0));
stu.setName(obj.optString("name" , ""));
stu.setSex(obj.optBoolean("sex" , true));
stu.setCellPhone(obj.optString("cellPhone" , ""));
System.out.println("学生:" + stu.toString());
String outputMsg = "Welcome!";
byte[] ouputData = outputMsg.getBytes();
outputStream.write(ouputData);
System.out.println("ECHO:" + outputMsg + "\n");
//关闭连接
conn.close();
}
}
}
2、客户端的代码
package my;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.json.JSONObject;
public class MyClient
{
public static void main(String[] args) throws IOException
{
//一个Scoket代表一路连接
Socket sock = new Socket();
//连接至服务器
sock.connect(new InetSocketAddress("127.0.0.1" , 2019));
//InputStream用于接收数据,OutputStreet用于发送数据
InputStream inputStream = sock.getInputStream();
OutputStream outputStream = sock.getOutputStream();
//发送数据
//创建一个学生对象
Student stu = new Student(2018001 , "小明" , true , "18825030000");
JSONObject json = new JSONObject(stu);
String outputMsg = json.toString(2);// "Hello";
byte[] outputData = outputMsg.getBytes("UTF-8");
outputStream.write(outputData);
System.out.println(">>" + outputMsg);
//接收数据
byte[] inputData = new byte[4000];
int n = inputStream.read(inputData);
String inputMsg = new String(inputData , 0 , n , "UTF-8");
System.out.println("<<" + inputMsg);
//关闭连接
sock.close();
}
}