IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Java TCP 和UDP daytime协议服务器和客户端 -> 正文阅读

[网络协议]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();
	}
}

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-09-04 17:54:21  更:2021-09-04 17:56:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/18 19:57:34-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码