简单的SocketExample
客户端
//---------------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的更多相关文章
- 【造轮子】打造一个简单的万能Excel读写工具
大家工作或者平时是不是经常遇到要读写一些简单格式的Excel? shit!~很蛋疼,因为之前吹牛,就搞了个这东西,还算是挺实用,和大家分享下. 厌烦了每次搞简单类型的Excel读写?不怕~来,喜欢流式 ...
- Fabio 安装和简单使用
Fabio(Go 语言):https://github.com/eBay/fabio Fabio 是一个快速.现代.zero-conf 负载均衡 HTTP(S) 路由器,用于部署 Consul 管理的 ...
- node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理
一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...
- 哪种缓存效果高?开源一个简单的缓存组件j2cache
背景 现在的web系统已经越来越多的应用缓存技术,而且缓存技术确实是能实足的增强系统性能的.我在项目中也开始接触一些缓存的需求. 开始简单的就用jvm(java托管内存)来做缓存,这样对于单个应用服务 ...
- 在Openfire上弄一个简单的推送系统
推送系统 说是推送系统有点大,其实就是一个消息广播功能吧.作用其实也就是由服务端接收到消息然后推送到订阅的客户端. 思路 对于推送最关键的是服务端向客户端发送数据,客户端向服务端订阅自己想要的消息.这 ...
- 我的MYSQL学习心得(一) 简单语法
我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...
- 使用 Nodejs 搭建简单的Web服务器
使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...
- ASP.NET Aries 入门开发教程2:配置出一个简单的列表页面
前言: 朋友们都期待我稳定地工作,但创业公司若要躺下,也非意念可控. 若人生注定了风雨飘摇,那就雨中前行了. 最机开始看聊新的工作机会,欢迎推荐,创业公司也可! 同时,趁着自由时间,抓紧把这系列教程给 ...
- 简单入门canvas - 通过刮奖效果来学习
一 .前言 一直在做PC端的前端开发,从互联网到行业软件.最近发现移动端已经成为前端必备技能了,真是不能停止学习.HTML5新增的一些东西,canvas是用的比较多也比较复杂的一个,简单的入门了一下, ...
随机推荐
- useradd命令详解
功能说明:建立用户帐号.语 法:useradd [-mMnr][-c <备注>][-d <登入目录>][-e <有效期限>][-f <缓冲天数>][-g ...
- python之函数式编程
python提供了支持函数式编程的简单机制: 1. map函数 2. filter函数 3. reduce函数. 典型的M/R计算模型. 但还是有点简单...
- Nginx模块开发1_明白自定义模块的编译流程
自定义模块的编译流程 --add-module参数 configure使用--add-module参数指定添加模块目录. config脚本 由--add-module指定的目录保存为$ngx-addo ...
- IOS开发之──应用之间调用(1)
iphone应用之间调用步骤: 1)在plist文件中,注册对外接口 在xcode group&files 里面,展开 resources选择<app>info.plist 鼠标右 ...
- MVC学习系列——RazorViewEngine扩展
有时候,我们的项目涉及到多种风格,我们可以通过扩展RazorViewEngine,这样就可以保持后台代码不发生变化. 新建类ThemeViewEngine继承于RazorViewEngine publ ...
- 【转载】IE6 PNG透明终极解决方案(打造W3Cfuns-IE6PNG最强帖)
原文地址:http://www.w3cfuns.com/thread-297-1-1.html 本文版权归W3Cfuns.com所有,转载需在文章页面明显位置以链接的方式给出原文链接,否则W3Cfun ...
- Swift Json 解析错误
昨天在开发公司的ios程序时,遇见一个json解析的问题,并且是一个非常奇怪的问题. 因为原来的代码比较复杂,所以对代码进行了一些简化,具体代码如下: 服务器返回格式(PHP): array( arr ...
- Xcode Provisioning 路径
~/Library/MobileDevice/Provisioning Profiles
- vc终端输入结束符
操作系统使用不同的值作为文件结束符.Windows上我们通过键入ctrl+z键作为文件结束符.Unix系统中,包括Mac OS-X机器,通常用ctrl+d作为文件结束符.用VC++6.0的时候,要输入 ...
- spoj 138
离散化 去掉重复点 排序 二分查找 #include<cstdio> #include<cstring> #include<algorithm> #define ...