服務端接收到客戶端傳送的檔名,並把檔案的內容返回給客戶端
阿新 • • 發佈:2019-02-04
public class ScoketService {
public static void server() {
System.out.println("-------------服務已啟動-------------");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(6666);
while (true) {
//接收一個客戶端的連線
Socket socket = serverSocket.accept();
// 獲取ip地址
InetAddress sourceIp = socket.getInetAddress();
System.out.println(sourceIp);
InputStream is = socket.getInputStream();
Scanner s = new Scanner(is);
OutputStream out = socket.getOutputStream();
while (s.hasNext()) {
// 1:我們拿到了客戶端輸入來的資訊
String str = s.nextLine();
System.out.println(str);
// 2:根據檔名,從檔案裡取出資料
String fileContent = "";
fileContent = getContentFromFile(str);
// 3:傳送內容到客戶端(迴應一下客戶)
PrintWriter pw = new PrintWriter(out);
pw.println(fileContent);
pw.flush();
}
is.close();
socket.close();
System.out.println(sourceIp+"已下線");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根據檔名,取出檔案中的內容
* @param filePath
* @return
*/
public static String getContentFromFile(String filePath) {
if(filePath.equals("ips.txt")){
String content ="";
try {
Scanner s = new Scanner(new File(filePath));
while(s.hasNext()){
content+=s.nextLine()+"\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return content;
}else{
return "File does not exist!!!!!!!!! ";
}
}
public static void main(String[] args) {
server();
}
}
public static void server() {
System.out.println("-------------服務已啟動-------------");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(6666);
while (true) {
//接收一個客戶端的連線
Socket socket = serverSocket.accept();
// 獲取ip地址
InetAddress sourceIp = socket.getInetAddress();
System.out.println(sourceIp);
InputStream is = socket.getInputStream();
Scanner s = new Scanner(is);
OutputStream out = socket.getOutputStream();
while (s.hasNext()) {
// 1:我們拿到了客戶端輸入來的資訊
String str = s.nextLine();
System.out.println(str);
// 2:根據檔名,從檔案裡取出資料
String fileContent = "";
fileContent = getContentFromFile(str);
// 3:傳送內容到客戶端(迴應一下客戶)
PrintWriter pw = new PrintWriter(out);
pw.println(fileContent);
pw.flush();
}
is.close();
socket.close();
System.out.println(sourceIp+"已下線");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根據檔名,取出檔案中的內容
* @param filePath
* @return
*/
public static String getContentFromFile(String filePath) {
if(filePath.equals("ips.txt")){
String content ="";
try {
Scanner s = new Scanner(new File(filePath));
while(s.hasNext()){
content+=s.nextLine()+"\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return content;
}else{
return "File does not exist!!!!!!!!! ";
}
}
public static void main(String[] args) {
server();
}
}