客户端
public class ClientDemo {
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 3333);
BufferedReader br = new BufferedReader(new FileReader("GuessGame.java"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
s.shutdownOutput();
BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
String client = brClient.readLine();
System.out.println(client);
br.close();
s.close();
}
}
服务器
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(3333);
while (true) {
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
线程
public class UserThread implements Runnable {
private Socket s;
public UserThread(Socket s) {
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
//BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java"));
String newName = System.currentTimeMillis()+".java";
BufferedWriter bw = new BufferedWriter(new FileWriter(newName));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
BufferedWriter bwServer = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
bwServer.write("文件上传成功");
bwServer.newLine();
bwServer.flush();
bw.close();
s.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
|
|