Java Socket简单的客服端及其服务器端
最近给别人写了个服务器读文件,然后传到客服端,客服端收到消息再写到客服机器中的一个socket程序,socket传输协议用的是TCP,读文件和写文件的路径都用properties配置文件来配置。
客服端文件源代码如下:
package javaSocket;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class SocketClient{
private Socket skClient;
public SocketClient(){
}
public void clientCreate(){
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream("d:\\test.properties"));
Properties p = new Properties();
p.load(in);
String path = p.getProperty("path1");
FileOutputStream fos = new FileOutputStream(path);
skClient = new Socket(InetAddress.getLocalHost(),8888);
System.out.println("向服务器发出链接请求!");
copyStream(skClient.getInputStream(),fos);
skClient.close();
fos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void copyStream(InputStream is, OutputStream os) throws IOException {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
line = reader.readLine();
while (line != null) {
writer.println(line);
line = reader.readLine();
}
writer.flush();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new SocketClient().clientCreate();
}
}
服务器端的源代码如下:
package javaSocket;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class SocketServer extends Thread{
private Socket skServer;
public SocketServer(Socket s){
this.skServer = s;
}
public void run(){
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream("d:\\test.properties"));
Properties p = new Properties();
p.load(in);
String path = p.getProperty("path2");
FileInputStream fis = new FileInputStream(path);
copyStream(fis,skServer.getOutputStream());
skServer.close();
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void copyStream(InputStream is, OutputStream os) throws IOException {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
line = reader.readLine();
while (line != null) {
writer.println(line);
line = reader.readLine();
}
writer.flush();
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器已经启动,已处于监听状态......");
while(true){
SocketServer ss = new SocketServer(server.accept());
System.out.println("成功响应客服端!");
ss.start();
}
}
}
配置属性文件test.properties:
path1=D:\\123.txt
path2=D:\\456.txt
因为写的时间比较急,所以很多地方需要修改。基本功能已经实现了。有兴趣就可以再修改完善。