8.13 Java 网络编程 TCP

跟python一样的操作方法 针对TCP的数据流需要连接 accept 针对UDP的数据报就不需要连接

服务器端:

import java.io.*;
import java.net.*;

public class Server extends Thread{
	public static <T> void pln(T x) {
		System.out.println(x);
	}
	private ServerSocket serverSocket;
	public Server (int port) throws IOException {
		serverSocket = new ServerSocket(port);
		serverSocket.setSoTimeout(10000);
	}
	public void run() {
		while (true) {
			try {
				pln("Waiting for remote connecting, the port is : " + serverSocket.getLocalPort() + "...");
				Socket server = serverSocket.accept();
				pln("Remote host address is :" + server.getRemoteSocketAddress());
				DataInputStream in = new DataInputStream(server.getInputStream());
				pln(in.readUTF());
				DataOutputStream out = new DataOutputStream(server.getOutputStream());
				out.writeUTF("Thanks for connecting... " + server.getLocalSocketAddress() + " Goodbye\n");
				server.close();
			} catch (SocketTimeoutException e1) {
				pln("Socket time out");
				e1.printStackTrace();
				break;
			} catch (IOException e2) {
				e2.printStackTrace();
				break;
			}
		}
	}
	public static void main(String[] args) {
		int port = Integer.parseInt(args[0]);
		try {
			Thread t = new Server(port);
			t.run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

客户端:

import java.net.*;
import java.io.*;

public class Client {
	static <T> void pln(T x) {
		System.out.println(x);
	}
	public static void main(String[] args) {
		String serverName = args[0];
		int port = Integer.parseInt(args[1]);
		try {
			pln("Connecting to host: " + serverName + "   port : " + port);
			Socket client =  new Socket(serverName, port);
			pln("Remote host address : " + client.getRemoteSocketAddress());
			OutputStream outToServer = client.getOutputStream();
			DataOutputStream out = new DataOutputStream(outToServer);
			
			out.writeUTF("Hello from " + client.getLocalSocketAddress());
			InputStream inFromServer = client.getInputStream();
			DataInputStream in = new DataInputStream(inFromServer);
			pln("Server response : " + in.readUTF());
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

posted @ 2023-08-13 16:30  N0zoM1z0  阅读(1)  评论(0编辑  收藏  举报