1. 程式人生 > >socket通訊實現server端和client端互發訊息

socket通訊實現server端和client端互發訊息

案例主要考察了socket、io流知識。

Server端程式碼:

ServerSocket server=new ServerSocket(1234);
		Socket client=server.accept();
		BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
		PrintWriter pw=new PrintWriter(client.getOutputStream());
		BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));
		while(true){
			String str=br.readLine();
			System.out.println("accept client info:"+str);
			String send=bw.readLine();
//			System.out.println("answer message...");
			pw.println("send:"+send);
			pw.println("server已接收info....");
			pw.flush();
			if(send.equals("交易結束"))
				break;
		}
		client.close();

client端程式碼:
Socket socket=new Socket(InetAddress.getLocalHost(),1234);
			BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));//接收server訊息
			PrintWriter pw=new PrintWriter(socket.getOutputStream());
			BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));//send info
			while(true){
				System.out.println("client begin send message...");
				String str=bw.readLine();
				pw.println("str:"+str);
				pw.flush();
				if(str.equals("交易結束")){
					break;
				}
				System.out.println("client:"+br.readLine());
			}
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

控制檯訊息:

client:

client begin send message...
?
client:send:交易結束
client begin send message...
交易結束

server:

accept client info:str:?
交易結束