tcpserver.java

来自「client server socket programs to learn s」· Java 代码 · 共 43 行

JAVA
43
字号
import java.util.*;
import java.io.*;
import java.net.*;

class TCPServer {

    public static void main (String args[]) throws Exception {
		// throws Exception here because don't want to deal
		// with errors in the rest of the code for simplicity.
		// (Note: NOT a good practice).

         //Welcome socket  ---- SOCKET 1
         int port = Integer.parseInt(args[0]);
		 ServerSocket serverSocket = new ServerSocket(port);
		 // waits for a new connection. Accepts connetion from multiple clients
		 while (true)
		 {
			 System.out.println("waiting for connection at 9000");
             //Connection socket  --- SOCKET 2
			 Socket s = serverSocket.accept();
			 System.out.println("connection established from " + s.getInetAddress());

			 // create a BufferedReader object to read strings from
			 // the socket. (read strings FROM CLIENT)
			 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			 String input = br.readLine();

			 //create output stream to write to/send TO CLINET
             DataOutputStream output = new DataOutputStream(s.getOutputStream());

			 // keep repeating until an empty line is read.
			 while (input.compareTo("") != 0) {
				 // convert input to upper case and echo back to
				 // client.
				 output.writeBytes(input.toUpperCase() + "\n");
				 input = br.readLine();
			}
			// close current connection
			s.close();
		 }
    }
}

⌨️ 快捷键说明

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