Java心得34

    今天跟大家分享一下:


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class MyServer {
private static boolean isRun = true;
    public MyServer(){
    try {
ServerSocket server = new ServerSocket(8080);

while(isRun){
Socket socket = server.accept();

new MyThread(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
   
    }
    public static void main(String[] args) {
MyServer m = new MyServer();
}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


public class MyThread implements Runnable{
private FilePress fp = new FilePress();
private Socket socket;
    public MyThread(Socket socket){
    this.socket = socket;
   
    Thread t = new Thread(this);
    t.start();
    }
@Override
public void run() {
InputStream in = null;
OutputStream out = null;

try {
in = socket.getInputStream();
out = socket.getOutputStream();

byte[]b = new byte[1024];
in.read(b);
String str = new String(b).trim();
fp.writeFile(str);
out.write("文件已保存".getBytes());
out.flush();

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}



import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class FilePress {
private static Properties pro = new Properties();
    public void writeFile(String str){
    String info = str.substring(str.indexOf("?")+1, str.lastIndexOf(" "));
        String[]x = info.split("&");
        String fileName = x[0].substring(x[0].indexOf("=")+1);
        for(int i = 1;i         String temp[] = x[i].split("=");
        pro.setProperty(temp[0], temp[1]);
        }
        try {
pro.store(new FileWriter(fileName+".properties"), null);
} catch (IOException e) {
e.printStackTrace();
}
    
    }
    
}



import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


import javax.swing.JOptionPane;


public class MyClient {
public MyClient(){
String str = JOptionPane.showInputDialog(null,"请输入消息");
try {
Socket socket = new Socket("127.0.0.1",8080);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();

out.write(str.getBytes());
out.flush();

byte[]b = new byte[1024];
in.read(b);
String info = new String(b).trim();
JOptionPane.showMessageDialog(null, "服务器回复:"+info);

} catch (Exception e) {
e.printStackTrace();

}




    public static void main(String[] args) {
MyClient m = new MyClient();
}
}

你可能感兴趣的:(心得)