`

Simple TCP example

    博客分类:
  • Java
阅读更多

 

Server:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
	public static void main(String[] args) throws Exception {
		ServerSocket serversocket = new ServerSocket(8000);
		Socket socket = null;
		InputStream ips = null;
		OutputStream ops = null;

		byte[] recvbuffer = new byte[1024];
		byte[] sendbuffer = new byte[1024];
		byte[] content = "Hello, This is server!".getBytes();
		System.arraycopy(content, 0, sendbuffer, 0, content.length);
		long index = 0, length = 0;

		for (;;) {
			try {
				socket = serversocket.accept();
				ips = socket.getInputStream();
				ops = socket.getOutputStream();

				System.out.println("Connected From: " + socket.getInetAddress()
						+ ":" + socket.getPort());

				index = 0;
				length = 0;
				long current = System.currentTimeMillis();

				for (;;) {
					// Thread.sleep(1);

					int available = ips.available();
					if (available >= recvbuffer.length) {
						ips.read(recvbuffer);
						length += recvbuffer.length;
						index++;
						current = System.currentTimeMillis();
						System.out.print("\rReceive: " + index + ", Length: "
								+ length);
						if (!new String(recvbuffer).trim().equalsIgnoreCase(
								"Hello, This is client!")) {
							System.err.println("Content Error!");
						}
					} else {
						if (System.currentTimeMillis() - current > 3000) {
							ops.write(sendbuffer);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				System.out.println("Total Length: "
						+ (length + ips.available()));

				if (ops != null) {
					ops.flush();
					ops.close();
				}
				if (ips != null) {
					ips.close();
				}
				if (socket != null) {
					socket.close();
				}
			}
		}
	}
}

Client:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {
	public static void main(String[] args) throws Exception {
		if (args.length < 3) {
			System.out
					.println("Usage:java TcpClient ServerIP ServerPort SendCount");
			return;
		}
		Socket socket = new Socket(InetAddress.getByName(args[0]),
				Integer.parseInt(args[1]));
		InputStream ips = socket.getInputStream();
		OutputStream ops = socket.getOutputStream();

		byte[] recvbuffer = new byte[1024];
		byte[] sendbuffer = new byte[1024];
		byte[] content = "Hello, This is client!".getBytes();
		System.arraycopy(content, 0, sendbuffer, 0, content.length);

		long index = 0, length = 0;
		System.out.println("Send start...");

		while (true) {
//			Thread.sleep(1);

			ops.write(sendbuffer);

			index++;
			length += sendbuffer.length;
			System.out.print("\rSend: " + index + ", "
					+ (index * 100 / Integer.parseInt(args[2])) + "%"
					+ ", Length: " + length);

			if (ips.available() >= recvbuffer.length) {
				ips.read(recvbuffer, 0, recvbuffer.length);

				if (!new String(recvbuffer).trim().equalsIgnoreCase(
						"Hello, This is server!")) {
					System.err.println("Content Error!");
				}
			}

			if (index >= Integer.parseInt(args[2])) {
				break;
			}
		}

		ops.flush();
		ops.close();
		ips.close();
		socket.close();
	}
}
 
0
0
分享到:
评论

相关推荐

    Simple-Windows-Socket-Server-Example.rar_simple_socket server

    标题中的“Simple-Windows-Socket-Server-Example.rar_simple_socket server”表明这是一个关于Windows平台上的简单Socket服务器示例的压缩文件。Socket编程是网络编程的基础,它允许程序通过网络发送和接收数据。在...

    A simple example of exchanging data across a network using t

    标题中的"A simple example of exchanging data across a network using t"似乎是指使用特定技术(可能是WinSock)在网络间交换数据的一个简单示例。这个示例可能是针对初学者或开发者,旨在教授如何利用网络通信类...

    TcpClientMFC.zip

    Simple tcp source example for your reference It is a visual studio mfc example

    CORBA技术及实例.rar_Java CORBA_corba_corba java_corba simple example_

    4. **GIOP(General Inter-ORB Protocol)和IIOP(Internet Inter-ORB Protocol)**:GIOP是ORB间通信的基础协议,而IIOP是GIOP在TCP/IP上的具体实现,用于传输CORBA消息。 5. **Servant和Stub**:Servant是服务器...

    Simple Client Server Chat Example:一个简单的聊天系统的例子-开源

    套接字部分旨在说明使用TCP / IP进行简单的通信是多么简单。 系统显示了如何通过网络交换和处理String。 在谈论大型应用程序时,这还不够,但是,请不要忘记HTTP使用字符串。 该项目包含服务器和客户端。 Main类中...

    java socket programming example

    Socket是TCP/IP协议族的一部分,它是两台计算机之间通信的端点。在Java中,`java.net.Socket`类代表客户端套接字,而`java.net.ServerSocket`类则用于服务器端,监听并接受来自客户端的连接。 1. **创建...

    精彩编程与编程技巧-SMTP协议简介 (Simple Mail Transfer Protocol)...

    ### SMTP协议简介 (Simple Mail Transfer Protocol) SMTP协议是互联网上用于传输电子邮件的标准协议之一,它在TCP/IP协议簇中占有重要地位。SMTP协议定义了一系列规则和命令,使得邮件客户端能够将邮件发送到邮件...

    NS by example

    **Example 1: Setting Up a Simple Network** Suppose you want to simulate a simple network consisting of two hosts connected by a router. Here’s how you can set up the simulation: 1. **Define Hosts**...

    C#实现应用程序发送邮件及同步TCP接收邮件

    本文将深入探讨如何使用C#实现应用程序发送邮件以及同步TCP接收邮件的功能,这涉及到网络通信中的SMTP(Simple Mail Transfer Protocol)和POP3(Post Office Protocol version 3)协议。 首先,让我们来理解SMTP...

    Send SMS example 2009_labview_发短信_may61p_电脑发短信_发邮件_

    同样,电脑发送电子邮件功能是通过Simple Mail Transfer Protocol (SMTP) 实现的。在LabVIEW中,可以使用SMTP服务器通信库,创建SMTP客户端,设置服务器地址、端口、用户名、密码等相关参数,然后构建邮件内容,...

    TCP-IP Sockets in Java. Practical Guide for Programmers

    * Provides code for all example programs via a companion Web site to let the reader see the important objects and methods in context and to understand the purpose of each line of code.

    光洋PLC例程源码SimpleIncoderprogramexample205series

    ### 光洋PLC例程源码Simple Incoder program example 205 series #### 知识点概览 本文将详细介绍与“光洋PLC例程源码Simple Incoder program example 205 series”相关的知识点,包括光洋PLC的基本概念、Simple ...

    A simple event-based WebSocket library for MATLAB..zip

    "A simple event-based WebSocket library for MATLAB" 提供了一种简单易用的解决方案,利用事件驱动模型来处理WebSocket的连接、消息发送和接收。 该库的核心概念可能包括以下几个部分: 1. **连接管理**:库应该...

    finagle-example

    这个命令会使用 Simple Build Tool (SBT) 构建工具,进入 "server" 子项目,并执行运行命令。SBT 是 Scala 开发的常用构建工具,它允许我们管理依赖、编译代码以及运行应用程序。 一旦服务器启动,我们可以通过 `nc...

    NS by examples.doc

    Simple Simulation Example A basic NS simulation involves creating nodes, connecting them with links, and configuring network components like traffic sources and routers. For instance, you could set up...

    端口查看工具

    o CurrPorts now displays a simple error message if it fails to close one or more TCP connections. * Version 2.01: o The 'Remote Address' and 'Local Address' columns are now sorted by the IP ...

    RemObjects SDK for Delphi

    Advanced This example shows how to create a proxy server to redirect the calls to another server without having to recreate the RODL file, thus allowing the use of the same types of the original ...

    simple-player-demo:使用 Flint 协议的简单视频播放器

    - 在Java中实现Flint协议解析和处理,通常需要对网络编程有深入理解,包括TCP/IP协议栈、数据包结构和解析算法。 - 使用Flint协议的播放器可能具备优化的带宽利用和适应性流媒体能力,确保在不同网络条件下能流畅...

Global site tag (gtag.js) - Google Analytics