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

📄 tcpserver.java

📁 Server端與Client端之間, 透過Socket建立TCP/IP的通訊模式
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;

public class TCPServer {
	public static String IP_ADDRESS;
	public final static int COMM_PORT = 2048;

	private InetAddress address = null;

	private ServerSocket serverSocket;
	private Socket socket;

	private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
	
	private final int interval = 60;

	private BufferedReader is;
	private PrintWriter os;
	private String data;

	public TCPServer() {		
		try {
			address = InetAddress.getLocalHost();
			IP_ADDRESS = address.getHostAddress();

			try {
				serverSocket = new ServerSocket(COMM_PORT);
				System.out.println("Server " + IP_ADDRESS + ", listening port " + COMM_PORT);
				socket = serverSocket.accept();
				is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				os = new PrintWriter(socket.getOutputStream());
			}
			catch(IOException ex) {
				System.err.println("IOException: " + ex.getMessage());
			}

			try {
				while(true) {
					data = is.readLine();
					if(data == null) break;
					Date dateTime = new Date();
					log(dateTime);
					echo(data, dateTime);
				}
				socket.close();
			}
			catch(IOException ex) {
				System.err.println("IOException: " + ex.getMessage());
			}
		}
		catch(UnknownHostException ex) {
			System.err.println("UnknownHostException: " + ex.getMessage());
		}
	}

	public void echo(String prompt, Date datetime) {
		if(prompt.equals("Are you here?")) {
			os.println(dateFormat.format(datetime.getTime()) + " Server>I am here!");
		}
		else {
			os.println(dateFormat.format(datetime.getTime()) + " Server>I receive the message: " + data);			
		}
		os.flush();
	}
	
	public void log(Date datetime) {
		try {
			File file = new File("tcpip.log");
			if(!file.exists()) file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file, true);
			String str = dateFormat.format(datetime.getTime()) + (char)9 + (data.equals("Are you here?")? "look-for": "send-echo") + (char)9 + data;
			for(int i = 0; i < str.length(); ++i) {
				fos.write(str.charAt(i));
			}
			fos.write('\r');
			fos.write('\n');
			fos.close();
		}
		catch(IOException ex) {
			System.err.println(ex);
		}
	}
	
	public static void main(String[] args) {
		TCPServer tcpServer = new TCPServer();
	}
}

⌨️ 快捷键说明

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