Server3.java
import java.net.*;
import java.io.*;
public class Server3{
private DataInputStream reader;
private DataOutputStream writer;
private ServerSocket server;
private Socket socket;
public Server3(){}
void startServer(){
try{
server=new ServerSocket(7777);
System.out.println("服务器套接字被成功创建");
while(true){
System.out.println("等待客户机连击请求");
socket=server.accept();
System.out.println("连接客户机完毕");
reader=new DataInputStream(socket.getInputStream());
writer=new DataOutputStream(socket.getOutputStream());
getCommand();
}
}catch(Exception e){
System.out.println(e);
}
}
void getCommand(){
try{
while(true){
String fileName=reader.readUTF();
writer.writeUTF(getFileInfo(fileName));
writer.flush();
System.out.println(fileName +"的信息传完毕");
}
}catch(Exception e){
}finally{
System.out.println("与客户机的连接中断");
try{
if(reader!=null) reader.close();
if(writer!=null) writer.close();
if(socket!=null) socket.close();
reader=null; writer=null; socket=null;
}catch(IOException ie){}
}
}
String getFileInfo(String fileName){
String fileInfo="";
try{
FileReader fr=new FileReader(fileName);
BufferedReader br=new BufferedReader(fr);
String temp;
while((temp=br.readLine())!=null)
fileInfo+= temp+"\n";
br.close();
}catch(FileNotFoundException fe){
fileInfo="文件不存在";
}catch(IOException ie){}
return fileInfo;
}
public static void main(String[] args){
Server3 server=new Server3();
server.startServer();
}
}
Client3.java
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class Client3 extends Frame{
private TextArea msgView=new TextArea();
private TextField sendBox=new TextField();
private DataInputStream reader;
private DataOutputStream writer;
Socket socket;
public Client3(String title){
super(title);
msgView.setEditable(false);
add(msgView,"Center");
add(sendBox,"South");
sendBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try{
writer.writeUTF(sendBox.getText());
writer.flush();
String fileInfo=reader.readUTF();
msgView.setText("< " + sendBox.getText()+"的内容 >\n\n");
msgView.append(fileInfo);
sendBox.setText("");
}catch(Exception ie){}
}
});
pack();
}
private void connect(){
try{
msgView.append("尝试与服务器连接\n");
socket=new Socket("127.0.0.1", 7777);
msgView.append("连接完毕丰... 请输入文件名\n");
reader=new DataInputStream(socket.getInputStream());
writer=new DataOutputStream(socket.getOutputStream());
}catch(Exception e){
msgView.append("连接失败..");
}
}
public static void main(String[] args){
Client3 client=new Client3("查看服务器系统文件");
client.setVisible(true);
client.connect();
}
}