TCP案例:客户端向服务端发送文件(即上传文件)
代码展示
其实上传文件只是在tcp点对点传输文本的基础上做了一些改进,大家可以点击这里参考java使用tcp协议实现点对点传输案例
客户端
package com.java.study;
import java.net.*;
import java.io.*;
import java.util.*;
public class client {
public static void main(String[] args) throws IOException {
InetAddress inetAddress=InetAddress.getLocalHost();
Socket socketclient=new Socket(inetAddress,8888);
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("f:\\target/java2/java3/java4.txt"));
OutputStream os=socketclient.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(os);
int input=-1;
while((input=bis.read())!=-1){
bos.write(input);
}
bos.flush();
socketclient.shutdownOutput();//本次流结束标识
bos.close();
os.close();
bis.close();
socketclient.close();
}
}
服务端
package com.java.study;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(8888);
Socket socketatclient=serverSocket.accept();
InputStream is=socketatclient.getInputStream();
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File("f:\\upload.md")));
BufferedInputStream bis=new BufferedInputStream(is);
int input=-1;
while((input=bis.read())!=-1){
bos.write(input);
}
if (bis!=null){
bis.close();
}
if (bos!=null){
bos.flush();
bos.close();
}
if (is!=null){
is.close();
}
if(socketatclient!=null){
socketatclient.close();
}
if (serverSocket!=null){
serverSocket.close();
}
}
}