TCP文件上传实现
客户端
public class TestClientDemo03 {
public static void main(String
[] args
) {
Socket socket
= null
;
OutputStream outputStream
= null
;
FileInputStream fileInputStream
= null
;
try {
InetAddress inetAddress
= InetAddress
.getByName("127.0.0.1");
int port
= 8989;
socket
= new Socket(inetAddress
,port
);
outputStream
= socket
.getOutputStream();
fileInputStream
= new FileInputStream(new File("FJ.jpg"));
byte[] buffer
= new byte[1024];
int len
;
while ((len
= fileInputStream
.read(buffer
)) != -1){
outputStream
.write(buffer
,0,len
);
}
}catch (Exception e
){
e
.printStackTrace();
}finally {
if (null
!= fileInputStream
){
try {
fileInputStream
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
if (null
!= outputStream
){
try {
outputStream
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
if (null
!= socket
){
try {
socket
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
}
}
}
服务端
public class TestServerDemo03 {
public static void main(String
[] args
) throws Exception
{
ServerSocket serverSocket
= null
;
Socket socket
= null
;
InputStream inputStream
= null
;
FileOutputStream fileOutputStream
= null
;
try {
serverSocket
= new ServerSocket(8989);
while (true){
socket
= serverSocket
.accept();
inputStream
= socket
.getInputStream();
fileOutputStream
= new FileOutputStream(new File("receive1.jpg"));
byte[] buffer
= new byte[1024];
int len
;
while ((len
= inputStream
.read(buffer
)) != -1){
fileOutputStream
.write(buffer
,0,len
);
}
}
}catch (Exception e
){
e
.printStackTrace();
}finally {
if (null
!= fileOutputStream
){
try {
fileOutputStream
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
if (null
!= inputStream
){
try {
inputStream
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
if (null
!= socket
){
try {
socket
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
if (null
!= serverSocket
){
try {
serverSocket
.close();
}catch (IOException e
){
e
.printStackTrace();
}
}
}
}
}