java-TCP协议发送和接收数据
Posted M_x_j
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java-TCP协议发送和接收数据相关的知识,希望对你有一定的参考价值。
服务器:
public class FileServerDemo {
public static void main(String[] args) throws IOException {
//创建服务器对象
ServerSocket ss = new ServerSocket(8080);
//监听
Socket s = ss.accept();
//包装通道内的输入流
BufferedInputStream bis = new BufferedInputStream(
s.getInputStream());
//把数据写入文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\Users\MA\Desktop\IOtest\copy.jpg"));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//把通道内的输出流包装
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
write.write("文件上传成功");
write.newLine();
write.flush();
//释放资源
bos.close();
s.close();
ss.close();
}
}
客户端:
public class FileClientDemo {
public static void main(String[] args) throws IOException {
//创建客户端对象
Socket s = new Socket("172.24.60.182",8080);
//读取文件的数据
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\Users\MA\Desktop\电路指导书\QQ图片20180627212519.jpg"));
//把通道内的输出流包装
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] bys = new byte[1024];
int len = 0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//给服务器一个反馈
s.shutdownOutput();//禁用输出流
//获取服务器的反馈信息
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = reader.readLine();
System.out.println("client:"+data);
bis.close();
s.close();
}
}
以上是关于java-TCP协议发送和接收数据的主要内容,如果未能解决你的问题,请参考以下文章
[转帖]Linux TCP/IP协议栈,数据发送接收流程,TCP协议特点
TCP/IP协议 怎么用JAVA发送和接收二进制数据 要具体实例