Java TCP 和UDP daytime协议服务器和客户端

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * Title: TcpDaytimeServer Description: TCP daytime server class for Network
 * Programming (LA01) course Author: William Chanrico Date: 7-June-2017
 */
public class TCPDaytimeServer {

	public static void main(String[] args) {

		new TCPDaytimeServer(13);
	}

	public TCPDaytimeServer(int port) {

		try (ServerSocket socket = new ServerSocket(port)) {

			System.out.println("TCP daytime server is listening on port " + port);

			while (true) {
				try (Socket conn = socket.accept()) {
					Date date = new Date();

					Writer osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
					osw.write(date.toString() + "\r\n");
					osw.flush();

					System.out.println(
							"Served a client from " + conn.getInetAddress().getHostName() + ":" + conn.getPort());
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
import java.net.*;
import java.io.*;

/**
 * This program is a socket client application that connects to a time server to
 * get the current date time.
 *
 * @author www.codejava.net
 */
public class TCPDaytimeClient {

	public static void main(String[] args) {
		String hostname = "localhost";
		int port = 13;

		try (Socket socket = new Socket(hostname, port)) {

			InputStream input = socket.getInputStream();
			InputStreamReader reader = new InputStreamReader(input);

			int character;
			StringBuilder data = new StringBuilder();

			while ((character = reader.read()) != -1) {
				data.append((char) character);
			}

			System.out.println(data);

		} catch (UnknownHostException ex) {

			System.out.println("Server not found: " + ex.getMessage());

		} catch (IOException ex) {

			System.out.println("I/O error: " + ex.getMessage());
		}
	}
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;

/**
 * Title: MultithreadedUdpDaytimeServer Description: Multithreaded UDP daytime
 * server class Author: William Chanrico Date: 7-June-2017
 */
public class UDPDaytimeServer {

	private DatagramSocket socket;

	public static void main(String[] args) {

		new UDPDaytimeServer(13);
	}

	public UDPDaytimeServer(int port) {
		try {
			socket = new DatagramSocket(port);

			System.out.println("UDP daytime server is listening on port " + port);

			while (true) {
				DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
				socket.receive(request);

				Thread task = new ServerThread(request);
				task.start();
			}
		} catch (SocketException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private class ServerThread extends Thread {
		private final DatagramPacket request;

		ServerThread(DatagramPacket request) {
			this.request = request;
		}

		@Override
		public void run() {
			InetAddress cliAddr = request.getAddress();
			int cliPort = request.getPort();

			try {
				String daytime = new Date().toString() + "\r\n";
				byte[] data = daytime.getBytes("UTF-8");

				DatagramPacket response = new DatagramPacket(data, data.length, cliAddr, cliPort);

				socket.send(response);

				System.out.println("Served a client from " + cliAddr + ":" + cliPort);
			} catch (UnsupportedEncodingException ex) {
				ex.printStackTrace();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;

/**
 * Connect to a daytime server using the UDP protocol. We use java.net instead
 * of java.nio because DatagramChannel doesn't honor the setSoTimeout() method
 * on the underlying DatagramSocket
 */
public class UDPDaytimeClient {
	public static void main(String args[]) throws java.io.IOException {
		// Figure out the host and port we're going to talk to
		String host = "localhost";
		int port = 13;

		// Create a socket to use
		DatagramSocket socket = new DatagramSocket();

		// Specify a 1-second timeout so that receive() does not block forever.
		socket.setSoTimeout(1000);

		// This buffer will hold the response. On overflow, extra bytes are
		// discarded: there is no possibility of a buffer overflow attack here.
		byte[] buffer = new byte[512];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port));

		// Try three times before giving up
		for (int i = 0; i < 3; i++) {
			try {
				// Send an empty datagram to the specified host (and port)
				packet.setLength(0); // make the packet empty
				socket.send(packet); // send it out

				// Wait for a response (or timeout after 1 second)
				packet.setLength(buffer.length); // make room for the response
				socket.receive(packet); // wait for the response

				// Decode and print the response
				System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII"));
				// We were successful so break out of the retry loop
				break;
			} catch (SocketTimeoutException e) {
				// If the receive call timed out, print error and retry
				System.out.println("No response");
			}
		}

		// We're done with the channel now
		socket.close();
	}
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
很抱歉,我无法打开您提供的文档。但是,我可以为您提供DAYTIME协议服务器客户程序的实现。 DAYTIME协议是一个简单的协议,它允许客户服务器交换当前日期和时间信息。服务器会将当前日期和时间以字符串形式发送给客户。下面是DAYTIME协议服务器客户程序的实现。 DAYTIME协议服务器程序实现: ```python import socket from datetime import datetime server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' port = 13 server_socket.bind((host, port)) server_socket.listen(5) print("Server listening on port ", port) while True: client_socket, address = server_socket.accept() print("Connection from ", address) current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") client_socket.send(current_time.encode()) client_socket.close() ``` DAYTIME协议客户程序实现: ```python import socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'localhost' port = 13 client_socket.connect((host, port)) data = client_socket.recv(1024) print("Current date and time: ", data.decode()) client_socket.close() ``` 在服务器,我们首先创建一个套接字并绑定到本地主机和指定的口。然后,我们开始监听客户连接请求。一旦我们接受客户连接请求,我们获取当前日期和时间并将其作为字符串发送给客户。最后,我们关闭客户套接字并继续等待其他客户连接。 在客户,我们创建一个套接字并连接到服务器的主机和口。一旦连接成功,我们接收从服务器发送的日期和时间信息并将其打印出来。最后,我们关闭客户套接字。 这就是DAYTIME协议服务器客户程序的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值