关闭

java 多线程Echo server和client 例子

标签: serversocket
120人阅读 评论(0) 收藏 举报
分类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ClientInfoStatus;


public class EchoMultiThreadServer {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ServerSocket server=null;
		try {
			server=new ServerSocket(8888);
			Socket client=null;
			boolean flag=true;
			while(flag){
				System.out.println("waiting....");
				client=server.accept();
				new Thread(new MultiThread(client)).start();;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

class MultiThread implements Runnable{
	Socket socket = null;
	PrintStream out = null;
	BufferedReader bur = null;

	public MultiThread(Socket s) {
		this.socket = s;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println(socket);

			bur = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			out = new PrintStream(socket.getOutputStream());

			boolean flag = true;
			while (flag) {
				String s = bur.readLine();
				if(s==null||"".equals(s)||"bye".equals(s)){
					flag=false;
				}
				else{
					out.println("Echo:"+s);
				}

			}
			System.out.println("close");
			bur.close();
			socket.close();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class EchoClient {
	public static void main(String[] args) throws IOException{
		Socket socket=new Socket("127.0.0.1",8888);
		BufferedReader buf=null;
		PrintStream out=null;
		BufferedReader input=null;
		boolean f=true;
		buf=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out=new PrintStream(socket.getOutputStream());
		input=new BufferedReader(new InputStreamReader(System.in));
		while(f){
			System.err.println("输入信息:");
			String s=input.readLine();
			out.println(s);
			if(s.equals("bye")){
				f=false;
			}else{
				String echo= buf.readLine();
				System.out.println(echo);
			}
			
		}
		buf.close();
		socket.close();
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:690次
    • 积分:26
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档