java网路编程之ECHO程序(多线程)

1.服务端程序:

package 网络编程.serviceSocket;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServe {
	public static void main(String[] args)throws Exception {
			
			//1.创建
			ServerSocket serverSocket = new ServerSocket(8888);
			//2.等待连接
			
			
			boolean flag = true ;
			while(flag){
				Socket socket = serverSocket.accept();
				new Thread(new Mythread(socket)).start();
			}
			serverSocket.close();
		}
	public static class Mythread implements Runnable{
		private Socket client ;
		public Mythread(Socket client) {
			this.client = client ;
		}
		@Override
		public void run() {
			try{
			boolean flag = true ;
			//3.客户端输入信息
			Scanner scanner = new Scanner(client.getInputStream());
			//必须换行
			scanner.useDelimiter("\n");
			//4.服务端输出信息
			PrintStream pw = new PrintStream(client.getOutputStream());
			
			while(flag){
				if(scanner.hasNext()){
					String str = scanner.next().trim();//防止有多个空格出现
					if("byby".equalsIgnoreCase(str)){//输入byby结束
						System.out.println("byby!!!");
						flag = false;
						break ;
					}
					pw.println("ECHO:"+ str);
				}
			}
			pw.close();
			scanner.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		
	}
	
}

2.客户端程序:

package 网络编程.clientSocket;

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
	public static void main(String[] args) throws Exception{
		//1.创建连接,设置地址和端口
		Socket socket = new Socket("localhost",8888);
		//2.用户输入信息
		Scanner keyScanner = new Scanner(System.in);
		keyScanner.useDelimiter("\n");
		//3.输入服务器的信息
		Scanner serveNet = new Scanner(socket.getInputStream());
		serveNet.useDelimiter("\n");
		//4.输出信息
		PrintStream pw = new PrintStream(socket.getOutputStream());
		boolean flag = true ;
		while(flag){
			System.out.print("请输入要发送的信息:");
			String str = null ;
			if(keyScanner.hasNext()){//判断是否有值
				str = keyScanner.next().trim();
				pw.println(str);//把信息发送给服务端
				if(serveNet.hasNext()){//如果服务端有回应
					System.out.println(serveNet.next().trim());
				}
				
			}
			if("byby".equalsIgnoreCase(str)){
				flag = false;
				break ;
			}
		}
		pw.close();
		serveNet.close();
		keyScanner.close();
		socket.close();
	}
}

你可能感兴趣的:(计算机,编程,java)