java通过socket通讯发送excel文件到c#端,excel文件乱码
java端socket,发送excel文件字节流
public boolean sendExcel() {
Socket socket;
ServerSocket ss;
DataOutputStream ps;
byte[] sendBytes = null;
try {
ss = new ServerSocket(this.port);
socket = ss.accept();
ps = new DataOutputStream(socket.getOutputStream());
fileinputstream = new FileInputStream(this.file);
sendBytes = new byte[fileinputstream.available()];
while (true) {
int read = 0;
if (fileinputstream != null) {
read = fileinputstream.read(sendBytes);
}
if (read == -1) {
break;
}
ps.write(sendBytes, 0, read);
}
Thread.sleep(5000);
ps.flush();
System.out.println("文件发送完成");
return true;
} catch (Exception e1) {
e1.printStackTrace();
return false;
}
}
c#客户端(控制台),接收excel字节流,并保存为文件
class Program
{
static void Main(string[] args)
{
string host;
int port;
string path;
try
{
//int port = 2000;
//string host = "127.0.0.1";
lable:
Console.Write("设定服务端ip:");
//"127.0.0.1:2000"
// host = Console.ReadLine();
host = "192.168.0.221";
Console.Write("设定服务端port:");
//port = Int32.Parse(Console.ReadLine());
port = 2000;
Console.WriteLine("服务端的socket地址为:{0}:{1}", host, port);
//创建终结点EndPoint
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口转化为IPEndPoint的实例
//创建Socket并连接到服务器
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 创建Socket
Console.WriteLine("Connecting...");
try
{
c.Connect(ipe); //连接到服务器
}
catch (Exception e)
{
Console.WriteLine("连接失败,需重试!");
goto lable;
}
//向服务器发送信息
string sendStr = "Hello,this is a socket test";
byte[] bs = Encoding.UTF8.GetBytes(sendStr); //把字符串编码为字节
Console.WriteLine("Send message");
c.Send(bs, bs.Length, 0); //发送信息
//接受从服务器返回的信息
string recvStr = "";
byte[] recvBytes = new byte[1048576];
int bytes;
StreamWriter writer;
Console.Write("请输入要保存的文件名:");
path = Console.ReadLine();
writer = new StreamWriter(path, false, System.Text.Encoding.UTF8);
//writer = new StreamWriter(path, false, System.Text.Encoding.Default);
//while(true)
{
bytes = c.Receive(recvBytes, recvBytes.Length, 0); //从服务器端接受返回信息
recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
//recvStr += Encoding.UTF8.GetString(recvBytes, 3, bytes-3);
//保存文件
// Console.WriteLine("client get message:{0}", recvStr); //回显服务器的返回信息
}
writer.Write(recvStr);
writer.Close();
Console.ReadLine();
//一定记着用完Socket后要关闭
c.Close();
}
catch (ArgumentException e)
{
Console.WriteLine("argumentNullException:{0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
}
Console.WriteLine("按任意键结束");
Console.ReadLine();
}
}
[解决办法]
bytes = c.Receive(recvBytes, recvBytes.Length, 0);
FileStream fsOut = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fsOut.Write(recvBytes, 0, bytes);
fsOut.Close();