⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tcpserverd.java

📁 培训的时候的代码
💻 JAVA
字号:
package day15;
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPServerD {

	
	public static void main(String[] args) {
		
			ServerSocket ss=null;
			Socket s=null;
			HashSet hs=new HashSet();
//			BufferedReader br=null;
//			PrintStream ps=null;
			try {
				ss=new ServerSocket(8888);
				while(true){
					s=ss.accept();
					hs.add(s);
					new ServerThreadA(s).start();
//					br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//					ps=new PrintStream(s.getOutputStream());
//					while(true){
//					String str=br.readLine();
//					if(str.equals("quit")){
//						System.out.println(s.getInetAddress()+"已经退出");
//						break;
//					}
//					System.out.println(s.getInetAddress()+":");
//					str=str.toUpperCase();
//					
//					ps.println(str);
//					ps.flush();
//					}
				}
					
			} catch (IOException e) {
				
				e.printStackTrace();
			}finally{
//				if(ps!=null)ps.close();
//				if(br!=null)
//					try {
//						br.close();
//					} catch (IOException e1) {
//						
//						e1.printStackTrace();
//					}
				if(s!=null)
					try {
						s.close();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				if(ss!=null){
					try {
						ss.close();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				}
			}

		}
		
		
		

	}



	class ServerThreadB extends Thread{
		BufferedReader br=null;
		PrintStream ps=null;
		Socket s;
		HashSet hs;
		public ServerThreadB(Socket s,HashSet hs){
			this.s=s;
			this.hs=hs;
			try {
				br=new BufferedReader(new InputStreamReader(s.getInputStream()));
				ps=new PrintStream(s.getOutputStream());
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}
		public void run(){
			while(true){
				
				try {
				String	str = br.readLine();
				
				if(str.equals("quit")){
					System.out.println(s.getInetAddress()+"已经退出");
					hs.remove(s);
					s.close();
					break;
				}
				System.out.println(s.getInetAddress()+":"+str);
				for(Object obj:hs){
					Socket socket=(Socket)obj;
					PrintStream ps=new PrintStream(socket.getOutputStream());
					ps.println(s.getInetAddress()+":"+str);
					ps.flush();
				}
				
				
//				str=str.toUpperCase();
				
//				ps.println(str);
//				ps.flush();
	} catch (IOException e) {
					
					e.printStackTrace();
				}
				}
		
		}
	}

	


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -