import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.util.*; class Conn extends Thread{
private JTextArea txt;
private Socket st;
private String msg = null;
private BufferedReader br = null;
private PrintStream ps;
public Conn(Socket st,JTextArea txt){
this.st = st;
this.txt = txt;
start();
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(st.getInputStream()));
ps = new PrintStream(new DataOutputStream(st.getOutputStream()));
}catch(Exception e){
System.err.println("input failed");
}
while(true){
try{
msg = br.readLine();//阻塞方法
txt.append("从客户端收到信息:"+msg+'\n');
txt.append("信息接受时间是:"+new Date()+"\n");
//创建读取文件线程,并将读取到的内容通过服务器发送出去
FileThread ft = new FileThread();
Thread t = new Thread(ft);
t.start();
while(ft.flag);
System.out.println(ft.readData);
Server.send(ft.readData); }catch(Exception e){
System.err.println("connection closed");
break;
}
}
}
public void send(String msg){
ps.println(msg);
} } class FileThread implements Runnable{
public String readData = "";
public static boolean flag = true;
public void run() {
readData = readFileByLines("D:\\Hello.txt");
flag = false;
System.out.println(readData);
} /**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public String readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
String tempString = null;
String readData = "";
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
int line = 1; // 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
// System.out.println("line " + line + ": " + tempString);
// line++;
readData = readData.concat(tempString);//字符串拼接推荐函数
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
} return readData;
} } public class Server extends JFrame{
private JTextArea txt;
private ServerSocket ss;
public String tempString = null;
private static java.util.List<Conn> conns = new ArrayList<Conn>();
public Server(){
txt = new JTextArea();
this.setTitle("服务器");
this.setLayout(new BorderLayout());
this.add(new JScrollPane(txt),BorderLayout.CENTER);
this.setSize(500,300);
this.setVisible(true); run();
}
public void run(){
try{
ss = new ServerSocket(3000);
}catch(Exception e){
System.err.println("open socket failed");
}
txt.append("服务器已经启动!"+"\n");
while(true){
try{
Socket st=ss.accept();
conns.add(new Conn(st,txt));
}
catch(IOException ex){
System.err.println(ex);
}
}
}
public static void send(String msg){
for(Conn c:conns)
c.send(msg);
} public static void main(String args[]){ Server myserver=new Server();
} }
另外一种写法: