没有联接到对方主机,你看看是不是Ip地址,或者端号写错了,
看一下我写的的文件传输吧
客户端代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class FileClient {
public static final String SRC_FILE="data.txt";
public static void main(String[] args) throws Exception {
start();
}
public static void start() throws Exception {
Socket s = new Socket("127.0.0.1", 9999);
File file = new File(SRC_FILE);
BufferedReader bfr = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
int posi = file.getName().lastIndexOf(".");
String suffix = file.getName().substring(posi);
System.out.println(suffix);
out.println(suffix);
String line = null;
while ((line = bfr.readLine()) != null) {
out.println(line);
}
s.shutdownOutput();//关闭客户端的输出流,相当于给流中加入一个结束标记
BufferedReader bufIn = new BufferedReader(new InputStreamReader(
s.getInputStream()));
System.out.println(bufIn.readLine());
bfr.close();
bufIn.close();
s.close();
}
}
服务器端代码:
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) throws Exception {
start();
}
public static void start() throws Exception {
ServerSocket server = new ServerSocket(9999);
System.out.println("服务已经启动.......");
Socket s = server.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + ".......connected");
BufferedReader bfr = new BufferedReader(new InputStreamReader(
s.getInputStream()));
// 获取文件扩展名
String suffix = bfr.readLine();
PrintWriter out = new PrintWriter(new FileWriter("server" + suffix),
true);
String line = null;
while ((line = bfr.readLine()) != null) {
out.println(line);
}
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println("上传成功");
out.close();
s.close();
server.close();
}
}
|