日期:2014-05-20 浏览次数:20758 次
public class ServerThread {
private int port = 8000;
private ServerSocket serverSocket;
private static ExecutorService executorService;
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8000);
while (true) {
Socket s = ss.accept();
System.out.println("服务器启动");
Thread th = new Thread(new ServerThread().Server(s));
System.out.println(th.getName());
th.start();
}
}
public static Runnable Server(Socket soc) {
final Socket socket = soc;
return new Runnable() {
String str = "";
public void run() {
try {
System.out.println("连接 " + socket.getInetAddress() + ":"
+ socket.getPort());
InputStreamReader in = new InputStreamReader(
socket.getInputStream());
// BufferedReader br=new BufferedReader(in);
// OutputStreamWriter out = new OutputStreamWriter(
// socket.getOutputStream());
int msg;
while ((msg = in.read()) > -1) {
str += (char) msg;
System.out.println(str + "起動");
}
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
}
客户端:
public class Client1 {
public static void main(String[] args) {
SingleThread(1).run();
}
public static Runnable SingleThread(final int id) {
return new Runnable() {
Socket socket;
int port = 8000;
String str = "";
public void run() {
System.out.println("线程"+id + ":开始");
try {
socket = new Socket("127.0.0.1", port);
InputStreamReader in = new InputStreamReader(
socket.getInputStream());
OutputStreamWriter out = new OutputStreamWriter(
socket.getOutputStream());
String msg = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter yout name");
msg = br.readLine();
out.write(msg);
System.out.println(msg);
out.flush();
int c = 0;
while ((c = in.read()) > -1) {
str += (char) c;
}
System.out.println(str);
if(str.equals("bye")){
out.close();
Thread.interrupted();
}
System.out.println("线程"+id + ":结束");
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
}
}