java socket封装_一个简单的socket封装

SSSocket, 意思是simple stupid socket interface

目的:

编写一个易于消息数据读写、非阻塞、跨平台的socket封装。目前用于手机网游客户端

优点:

1.采用非阻塞的连接和IO,即使是单线程也不会阻塞UI

2.提供读写buffer

3.对完整消息读取友好的API

缺点:

1.单线程使用方式,目前考虑是游戏的每一帧,非阻塞的读写一次数据。与多线程或者阻塞IO方式相比,读写速度上差了一些

2.buffer使用的只是原生数组。从缓冲区取出数据后,缓冲区尾部未读取数据会用内存拷贝的方式移动到头部

接口:

//create a socket , ready to connect to host define by host_name and port

struct ssso* ssso_new(const char* host_name, int port);

//close socket

void ssso_free(struct ssso* so);

//update socket, write data from buffer to socket, and if there is data readable, it return 1

int ssso_check(struct ssso* so);

//peek whether has data of size in read buffer, return data or NULL

void* ssso_peek(struct ssso* so, size_t size);

//discard data of size in read buffer, mainly us

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的Socket类用于实现网络通信中的客户端和服务器端之间的传输。为了方便使用,我们可以对Socket进行封装。下面是一个简单Socket封装示例: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class MySocket { private Socket socket; private InputStream input; private OutputStream output; public MySocket(String host, int port) throws UnknownHostException, IOException { socket = new Socket(host, port); input = socket.getInputStream(); output = socket.getOutputStream(); } public void write(String message) throws IOException { output.write(message.getBytes()); output.flush(); } public String read() throws IOException { byte[] buffer = new byte[1024]; int count = input.read(buffer); return new String(buffer, 0, count); } public void close() throws IOException { socket.close(); } } ``` 这个示例中,我们对Socket进行了简单封装,添加了write、read和close方法。其中,write方法用于向服务器端发送消息,read方法用于从服务器端接收消息,close方法用于关闭Socket连接。 使用时,我们可以这样调用: ```java MySocket socket = new MySocket("localhost", 8080); socket.write("Hello, world!"); String response = socket.read(); System.out.println(response); socket.close(); ``` 这样,我们就可以通过MySocket类方便地实现客户端和服务器端之间的通信。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值