黑马程序员技术交流社区
标题:
网络编程
[打印本页]
作者:
826278117
时间:
2019-5-31 14:47
标题:
网络编程
public class ClientDemo {
public static void main(String[] args) throws IOException {
//创建客户端Socket对象
Socket s = new Socket("192.168.1.66",10000);
//封装文本文件的数据
BufferedReader br = new BufferedReader(new FileReader("myNet\\InetAddressDemo.java"));
//封装输出流写数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line=br.readLine())!=null) {
bw.write(line);
bw.newLine();
bw.flush();
}
s.shutdownOutput();
//接收反馈
BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = brClient.readLine(); //等待读取数据
System.out.println("服务器的反馈:" + data);
//释放资源
br.close();
s.close();
}
}
public class ServerThread implements Runnable {
private Socket s;
public ServerThread(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
//接收数据写到文本文件
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//解决名称冲突问题
int count = 0;
File file = new File("myNet\\Copy["+count+"].java");
while (file.exists()) {
count++;
file = new File("myNet\\Copy["+count+"].java");
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String line;
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();
//释放资源
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ServerDemo {
public static void main(String[] args) throws IOException {
//创建服务器Socket对象
ServerSocket ss = new ServerSocket(10000);
while (true) {
//监听客户端连接,返回一个对应的Socket对象
Socket s = ss.accept();
//为每一个客户端开启一个线程
new Thread(new ServerThread(s)).start();
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2