?用户端:
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpDemoSend2 {
public static void main(String[] args) throws Exception {
//发送端建立连接
Socket socket = new Socket("localhost", 10090);
//读取文件后将数据写入IO流传输
OutputStream outputStream = socket.getOutputStream();
FileInputStream fs = new FileInputStream("a.txt");
//写出文件
byte[] bytes = new byte[1024];
int len=0;
while((len=fs.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
//通知服务器传输结束了
socket.shutdownOutput();
//读取服务端的反馈
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = socket.getInputStream();
byte[] bytes1 = new byte[1024];
int len2=0;
while((len2=inputStream.read(bytes1))!=-1){
bos.write(bytes1,0,len2);
}
System.out.println(bos.toString());
//关闭资源
bos.close();
inputStream.close();
fs.close();
outputStream.close();
socket.close();
}
}
?客服端:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo2 {
public static void main(String[] args) throws Exception{
//创建Socket连接
ServerSocket serverSocket = new ServerSocket(10090);
//监听客户端的连接
Socket accept = serverSocket.accept();
//通过输入流获取送端传来的数据
InputStream inputStream = accept.getInputStream();
//文件输出
byte[] bytes = new byte[1024];
int len=0;
//管道流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len=inputStream.read(bytes))!=-1){
bos.write(bytes,0,len);
}
System.out.println(bos.toString());
//写一个文件反馈
OutputStream outputStream = accept.getOutputStream();
outputStream.write("文件接受完毕".getBytes());
//关闭资源
outputStream.close();
bos.close();
inputStream.close();
accept.close();
}
}
|