数据发送端(客户端):
//创建一个Socket对象,连接IP地址为192.168.101.56的服务器的9002端口
Socket s = new Socket("192.168.101.56",9002);
byte[] content=new byte[100];
content[0]=(byte) 0xE2;
content[1]=(byte) 0x5C;
String fix="HHCYFI";
byte[] b= fix.getBytes();
for(int i=0;i<b.length;i++){
content[i+2]=b[i];
}
//传输字节流
DataOutputStream output=new DataOutputStream(s.getOutputStream());
output.write(content, 0, content.length);
System.out.println();
System.out.print("发送内容为:");
for(int i=0;i<content.length;i++)
System.out.print(content[i]);
output.close();
s.close(); //关闭Socket连接
数据接收端(服务器端):
ServerSocket ss = new ServerSocket(9002); //创建一个Socket服务器,监听9002端口
Socket s = ss.accept();//利用Socket服务器的accept()方法获取客户端Socket对象。
//获取二进制流
DataInputStream input=new DataInputStream(s.getInputStream());
byte[] buffer = new byte[20480];
//消息长度
int rlength=input.read(buffer, 0, 20480);
System.out.println();
System.out.println("接收的消息长度:"+rlength);
//传输的实际byte[]
byte[] buffer1 = new byte[rlength];
for(int i=0;i<buffer1.length;i++){
buffer1[i]=buffer[i];
}
String messageContent1=new String(buffer1,"GBK").toString().trim();
System.out.println("接收的消息(gbk转码):"+messageContent1);
String messageContent=new String(buffer,0,rlength).toString().trim();
System.out.println("接收的消息:"+messageContent);
原文:http://www.cnblogs.com/lan-writenbook/p/5090179.html