使用socket写一段代码
时间: 2024-04-24 21:23:49 浏览: 126
使用socket写一段代码可以实现客户端与服务器之间的通信。以下是一个简单的示例代码:
客户端代码:
```javascript
const io = require('socket.io-client');
var socket = io.connect('http://localhost:8880');
socket.on('connect', function () {
console.log('Connection with Server established!');
socket.emit('messages', 'Client has established connection with Server');
});
socket.on('messages_jerry', function (data) {
console.log("Data sent from Server: " + JSON.stringify(data, null, 2));
socket.emit('messages', { my: 'data sent from Client' });
});
socket.on('messages', function (data) {
console.log("Data received from Server: " + JSON.stringify(data, null, 2));
});
```
服务器端代码:
```javascript
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8880);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("Connection coming from client: " + socket.id);
socket.emit('messages_jerry', { hello: 'world greeting from Server!' });
socket.on('messages', function (data) {
console.log("Data received from Client: " + JSON.stringify(data, null, 2));
});
});
```
这段代码实现了一个简单的客户端与服务器之间的通信。客户端通过socket.io连接到服务器,并在连接建立后发送一条消息给服务器。服务器接收到消息后,会发送一条回复消息给客户端。客户端和服务器都会打印出收到的消息内容。
请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体需求进行修改和扩展。
#### 引用[.reference_title]
- *1* *2* [一段最简单的使用socket.io进行服务器和客户端通信的例子代码](https://blog.csdn.net/i042416/article/details/88344872)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [c++socket 心跳机制代码](https://blog.csdn.net/yang_0103/article/details/101148622)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文