首页 > 代码库 > SocketServer 服务器

SocketServer 服务器

package com.boco.socketTest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

// 使用 OutputStreamWriter
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8765);
System.out.println("建立Server,PORT为8765。");
int i = 0;
int j = 1;


Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());



while (true) {
if(i==1){
break;
}
LineNumberReader wt = new LineNumberReader(new InputStreamReader(
new FileInputStream("D:/file/4813.txt")));
String str = wt.readLine();
while (str != null) {


System.out.println("str=" + str);
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}


str = wt.readLine();
}
// client.close();
i++;


}
}

}


本程序可以作为一个SocketServer服务器,读取本地文件,创建一个端口监听,等待客户端连接,然后发送读取的到的文件字符流, 其中"D:/file/4813.txt"为所要读取的文件存放路径