上一篇为大家介绍了利用Java程序发送post请求来传递文件流,但是却有大小限制,那么我们这次就来写一个socket,通过网络套接字来传递来往于客户端和服务器的文件。
我想大家对于java 的socket编程不会太陌生,那我就直接切入主题,分别编写服务器和客户端代码:
Server:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
/**
* @param args
*/
public static void main(String[] args) {
//ServerSocket server;
Long beginTime = null;
try {
ServerSocket server = new ServerSocket(1234);
while (true) {
final Socket sk = server.accept();
//通过套接字来发送文本
InputStream inStream = sk.getInputStream();
OutputStream outStream = sk.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
out.println("the program is beginning:");
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
out.println("Echo" + line);
if (line.trim().equals("bye")) {
done = true;
}
}
sk.close();
/*new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
//System.out.println(br.readLine());
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
}
} catch (IOException e) {
System.out.println("fail");
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// 创建套接字
Socket sk;
PrintStream ps;
//Temp temp = Temp.getInstance();
//temp.setSEND_TIME(System.currentTimeMillis());
//Long beginTime = temp.getSEND_TIME();
//System.out.println(beginTime);
try {
sk = new Socket("localhost", 1234);
ps = new PrintStream(sk.getOutputStream());
//读取文件
File file = new File("E:/toodou_work/testSmall.csv");
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str);
}
String content = sb.toString();
ps.print(content);
sk.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("link to server is fail");
e.printStackTrace();
}
}
}