客户端
//---------------VerySimpleClient.java
package SocketExample; // Tue Nov 2 18:34:53 EST 2004
//
// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain. Share and enjoy. Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException; public class VerySimpleClient {
private String serverHostname = null;
private int serverPort = 0;
private byte[] data = null;
private Socket sock = null;
private InputStream sockInput = null;
private OutputStream sockOutput = null; public VerySimpleClient(String serverHostname, int serverPort, byte[] data){
this.serverHostname = serverHostname;
this.serverPort = serverPort;
this.data = data;
} public void sendSomeMessages(int iterations) {
System.err.println("Opening connection to "+serverHostname+" port "+serverPort);
try {
sock = new Socket(serverHostname, serverPort);
sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
}
catch (IOException e){
e.printStackTrace(System.err);
return;
} System.err.println("About to start reading/writing to/from socket."); byte[] buf = new byte[data.length];
int bytes_read = 0;
for(int loopi = 1; loopi <= iterations; loopi++) {
try {
sockOutput.write(data, 0, data.length);
bytes_read = sockInput.read(buf, 0, buf.length);
}
catch (IOException e){
e.printStackTrace(System.err);
}
if(bytes_read < data.length) {
System.err.println("run: Sent "+data.length+" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
}
else {
System.err.println("Sent "+bytes_read+" bytes to server and received them back again, msg = "+(new String(data)));
} // Sleep for a bit so the action doesn't happen to fast - this is purely for reasons of demonstration, and not required technically.
try { Thread.sleep(50);} catch (Exception e) {};
}
System.err.println("Done reading/writing to/from socket, closing socket."); try {
sock.close();
}
catch (IOException e){
System.err.println("Exception closing socket.");
e.printStackTrace(System.err);
}
System.err.println("Exiting.");
} public static void main(String argv[]) {
String hostname = "localhost";
int port = 54321;
byte[] data = "Hello World".getBytes(); VerySimpleClient client = new VerySimpleClient(hostname, port, data);
client.sendSomeMessages(100);
}
}
服务端:
//-------------VerySimpleServer.java
package SocketExample; // Tue Nov 2 18:33:43 EST 2004
//
// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain. Share and enjoy. Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException; // An example of a very simple socket server. Start by looking at the
// static main() method at the bottom of this file.
public class VerySimpleServer {
private int serverPort = 0;
private ServerSocket serverSock = null; public VerySimpleServer(int serverPort) {
this.serverPort = serverPort; try {
serverSock = new ServerSocket(serverPort);
}
catch (IOException e){
e.printStackTrace(System.err);
}
} // All this method does is wait for some bytes from the
// connection, read them, then write them back again, until the
// socket is closed from the other side.
public void handleConnection(InputStream sockInput, OutputStream sockOutput) {
while(true) {
byte[] buf=new byte[1024];
int bytes_read = 0;
try {
// This call to read() will wait forever, until the
// program on the other side either sends some data,
// or closes the socket.
bytes_read = sockInput.read(buf, 0, buf.length); // If the socket is closed, sockInput.read() will return -1.
if(bytes_read < 0) {
System.err.println("Tried to read from socket, read() returned < 0, Closing socket.");
return;
}
System.err.println("Received "+bytes_read
+" bytes, sending them back to client, data="
+(new String(buf, 0, bytes_read)));
sockOutput.write(buf, 0, bytes_read);
// This call to flush() is optional - we're saying go
// ahead and send the data now instead of buffering
// it.
sockOutput.flush();
}
catch (Exception e){
System.err.println("Exception reading from/writing to socket, e="+e);
e.printStackTrace(System.err);
return;
}
} } public void waitForConnections() {
Socket sock = null;
InputStream sockInput = null;
OutputStream sockOutput = null;
while (true) {
try {
// This method call, accept(), blocks and waits
// (forever if necessary) until some other program
// opens a socket connection to our server. When some
// other program opens a connection to our server,
// accept() creates a new socket to represent that
// connection and returns.
sock = serverSock.accept();
System.err.println("Have accepted new socket."); // From this point on, no new socket connections can
// be made to our server until we call accept() again. sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
}
catch (IOException e){
e.printStackTrace(System.err);
} // Do something with the socket - read bytes from the
// socket and write them back to the socket until the
// other side closes the connection.
handleConnection(sockInput, sockOutput); // Now we close the socket.
try {
System.err.println("Closing socket.");
sock.close();
}
catch (Exception e){
System.err.println("Exception while closing socket.");
e.printStackTrace(System.err);
} System.err.println("Finished with socket, waiting for next connection.");
}
} public static void main(String argv[]) {
int port = 54321;
VerySimpleServer server = new VerySimpleServer(port);
server.waitForConnections();
}
}

简单的SocketExample的更多相关文章

  1. 【造轮子】打造一个简单的万能Excel读写工具

    大家工作或者平时是不是经常遇到要读写一些简单格式的Excel? shit!~很蛋疼,因为之前吹牛,就搞了个这东西,还算是挺实用,和大家分享下. 厌烦了每次搞简单类型的Excel读写?不怕~来,喜欢流式 ...

  2. Fabio 安装和简单使用

    Fabio(Go 语言):https://github.com/eBay/fabio Fabio 是一个快速.现代.zero-conf 负载均衡 HTTP(S) 路由器,用于部署 Consul 管理的 ...

  3. node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理

    一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...

  4. 哪种缓存效果高?开源一个简单的缓存组件j2cache

    背景 现在的web系统已经越来越多的应用缓存技术,而且缓存技术确实是能实足的增强系统性能的.我在项目中也开始接触一些缓存的需求. 开始简单的就用jvm(java托管内存)来做缓存,这样对于单个应用服务 ...

  5. 在Openfire上弄一个简单的推送系统

    推送系统 说是推送系统有点大,其实就是一个消息广播功能吧.作用其实也就是由服务端接收到消息然后推送到订阅的客户端. 思路 对于推送最关键的是服务端向客户端发送数据,客户端向服务端订阅自己想要的消息.这 ...

  6. 我的MYSQL学习心得(一) 简单语法

    我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...

  7. 使用 Nodejs 搭建简单的Web服务器

    使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...

  8. ASP.NET Aries 入门开发教程2:配置出一个简单的列表页面

    前言: 朋友们都期待我稳定地工作,但创业公司若要躺下,也非意念可控. 若人生注定了风雨飘摇,那就雨中前行了. 最机开始看聊新的工作机会,欢迎推荐,创业公司也可! 同时,趁着自由时间,抓紧把这系列教程给 ...

  9. 简单入门canvas - 通过刮奖效果来学习

    一 .前言 一直在做PC端的前端开发,从互联网到行业软件.最近发现移动端已经成为前端必备技能了,真是不能停止学习.HTML5新增的一些东西,canvas是用的比较多也比较复杂的一个,简单的入门了一下, ...

随机推荐

  1. python之else总结

    python中除了if...elif...else..还有while...else, for...else..., try...except...else...finally... 不管哪种else, ...

  2. 【python】 入门 - 函数式编程

    函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数 http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8b ...

  3. Ubuntu中NetBeans C/C++配置、编译

    系统环境:Ubuntu 9.04软件环境:NetBeans 6.7.1 C/C++ .JDK1.6.0_16本次目的:完成NetBeans 6.7.1 C/C++ 的配置工作.编译测试及对中文支持 首 ...

  4. C#TCPClient应用-一个简单的消息发送和接收

    TcpSend窗口用于发送消息,另外写一个用于接收消息的应用程序,消息接受到以后,必须要关闭接收消息的窗口,才能在接收新的消息,不知道怎么能解决这个问题. 源代码: 发送消息的窗口代码 using S ...

  5. SqlServer维护计划

    http://blog.csdn.net/yunye114105/article/details/6594826

  6. topcoder 673

    DiV1 300:给一组士兵再给一组战马都有权值. 安排战马的顺序的方案数,是第一个士兵和其战马的权值乘积最大. 做法:随便暴力就好. 枚举战马和第一个士兵匹配.其他士兵按权值从大到小排序,战马权值按 ...

  7. 浅析JVM内存结构和6大区域(转)

    其实对于我们一般理解的计算机内存,它算是CPU与计算机打交道最频繁的区域,所有数据都是先经过硬盘至内存,然后由CPU再从内存中获取数据进行处理,又将数据保存到内存,通过分页或分片技术将内存中的数据再f ...

  8. 剑指offer--面试题16

    #include<stack> //思路:遍历链表过程中,将各个指针入栈,再出栈进行反转 ListNode* ReverseList(ListNode* pHead) { if(pHead ...

  9. 提高jQuery执行效率需要注意几点

    1. 使用最新版本的jQuery jQuery的版本更新很快,你应该总是使用最新的版本.因为新版本会改进性能,还有很多新功能. 下面就来看看,不同版本的jQuery性能差异有多大.这里是三条最常见的j ...

  10. IMP不到指定的表空间

    ==============================================================================只导dmp文件中的几个表数据,解决导入时ta ...