Java网络编程笔记5

Java网络编程笔记4中我们看到了客户端与服务器通信的过程,只是在前面的程序只是单个客户端与服务器通信 的例子。

接下来我们看如何实现多个客户端与服务器通信,对于服务器来说,它要为每个客户端请求的Socket建立一个线程,并通过它进行通信。

在这里创建一个线程类用来管理Socket:

<span style="font-size:18px;">public class ServerThread extends Thread {
	private Socket socket;
	private int num;
	public ServerThread(Socket socket,int num){
		this.socket=socket;
		this.num=num;
	}
	@Override
	public void run() {
		try {
			InputStream is=socket.getInputStream();
			OutputStream os=socket.getOutputStream();
			DataInputStream dis=new DataInputStream(is);
			String request=dis.readLine();
			System.out.println(request);
			PrintStream ps=new PrintStream(os);
			ps.print("这是服务器发来的---->");
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}</span>

接着运行主程序与客户端进行通信:

<span style="font-size:18px;">public class Server {

	public static void main(String[] args) {
		try {
			ServerSocket ss=new ServerSocket(3000);
			int clientnum=0;
			while(true){
				ServerThread st=new ServerThread(ss.accept(),clientnum);
				st.start();
				System.out.println(clientnum++);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}</span>

客户端与前面的并无差别:

<span style="font-size:18px;">public class Client {

	public static void main(String[] args) {
		try {
			Socket socket = new Socket("192.168.12.112", 3000);
			
			BufferedReader bfr = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String request=bfr.readLine();
			System.out.println(request);
			OutputStream outputStream = socket.getOutputStream();
			PrintStream printStream = new PrintStream(outputStream);
			printStream.print("Client--->");
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}</span>


转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/42803955   情绪控_ 


©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页