运用tcp协议创建上传文件

Posted windzly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运用tcp协议创建上传文件相关的知识,希望对你有一定的参考价值。

牢记buffered需要刷新flush

package loadfile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		Socket s = new Socket("192.168.2.143",10003);
		BufferedReader br = new BufferedReader(new FileReader("client.txt"));
		BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		
		int ch = 0;
		while((ch = br.read()) != -1)
		{
			bwout.write(ch);
			bwout.flush();
		}
		s.shutdownOutput();
		
		BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String line = null;
		line = brin.readLine();
		System.out.println(line);
		
		
		br.close();
		s.close();
		bwout.close();
		brin.close();
	}

}

package loadfile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ServerSocket ss = new ServerSocket(10003);
		
		Socket s = ss.accept();
		BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream()));
		BufferedWriter brw = new BufferedWriter(new FileWriter("server.txt"));
		
		String line = null;
		while((line = brin.readLine()) != null)
		{
			brw.write(line);
			brw.newLine();
			brw.flush();
		}
		
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		out.write("上传成功");
		
		ss.close();
		out.close();
		brin.close();
		brw.close();
	}

}

  

以上是关于运用tcp协议创建上传文件的主要内容,如果未能解决你的问题,请参考以下文章

基于tcp协议的登录,文件上传和下载

关于TCP协议在项目中的运用

使用TCP协议写一个可以上传文件的服务器和客户端

java 26 - 8 网络编程之 TCP协议上传图片

JAVA 基于TCP协议的一对一,一对多文件传输实现

C# winfrom将文件通过IIS(http协议)上传到服务器上