客户端:
package com.ffyc.javanet.demo2;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",9999);
FileInputStream fin = new FileInputStream("D:/temp.txt");
OutputStream output = socket.getOutputStream();
byte[] b = new byte[100];
int size = 0;
while ((size = fin.read(b)) != -1) {
output.write(b, 0, size);
}
socket.shutdownOutput();//客户端告诉服务器已经发送完毕
System.out.println("发送完毕");
DataInputStream input = new DataInputStream(socket.getInputStream());
System.out.println( input.readUTF());
}
}
服务器端:
package com.ffyc.javanet.demo2;
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(9999);
System.out.println("服务器准备就绪!");
Socket socket = serverSocket.accept();
System.out.println("服务器端连接成功");
InputStream input = socket.getInputStream();
FileOutputStream fout = new FileOutputStream("D:/temp1.txt");
byte[] b = new byte[100];
int size = 0;
while ((size = input.read(b)) != -1) {
fout.write(b, 0, size);
}
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("服务器收到");
}
}
运行结果:
暑期编程PK赛 得CSDN机械键盘等精美礼品!



