tcpserverc.java

来自「培训的时候的代码」· Java 代码 · 共 108 行

JAVA
108
字号
package day15;
import java.io.*;
import java.net.*;
public class TCPServerC {

	
	public static void main(String[] args) {
		ServerSocket ss=null;
		Socket s=null;
		BufferedReader br=null;
		PrintStream ps=null;
		try {
			ss=new ServerSocket(8888);
			while(true){
				s=ss.accept();
				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 ServerThreadA extends Thread{
	BufferedReader br=null;
	PrintStream ps=null;
	Socket s;
	
	public ServerThreadA(Socket s){
		this.s=s;
		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()+"已经退出");
				break;
			}
			System.out.println(s.getInetAddress()+":");
			str=str.toUpperCase();
			
			ps.println(str);
			ps.flush();
} catch (IOException e) {
				
				e.printStackTrace();
			}
			}
	}
}

⌨️ 快捷键说明

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