server.java

来自「client server using socket programing 」· Java 代码 · 共 43 行

JAVA
43
字号
import java.net.*;
import java.io.*;
public class Server {
  public static void main(String[] ar) {
	int port = 6666; // just a random port. make sure you enter something between 1025 and 65535.
 
 	try {
    	ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.

    	System.out.println("Waiting for a client...");
 		Socket socket = ss.accept(); // make the server listen for a connection, and let you know when it gets one.
 		System.out.println("Got a client :) ... Finally, someone saw me through all the cover!");
    	System.out.println();


 		// Get the input and output streams of the socket, so that you can receive and send data to the client.
    	InputStream sin = socket.getInputStream();
    	OutputStream sout = socket.getOutputStream();
 		// Just converting them to different streams, so that string handling becomes easier.


    	DataInputStream in = new DataInputStream(sin);
    	DataOutputStream out = new DataOutputStream(sout);

 		String line = null;
    	
    	while(true) {
 			line = in.readUTF(); // wait for the client to send a line of text.

 			System.out.println("The dumb client just sent me this line : " + line);
    		System.out.println("I'm sending it back...");

 			out.writeUTF(line); // send the same line back to the client.
    		out.flush(); // flush the stream to ensure that the data reaches the other end.

 			System.out.println("Waiting for the next line...");
    		System.out.println();
		}
	}catch(Exception x) {
		x.printStackTrace();
	}
  }
}

⌨️ 快捷键说明

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