import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import { io } from 'socket.io-client';
export const Chat = () => {
const [chatList, setChatList] = useState([]);
useEffect(() => {
// 1 建立连接
// http://toutiao.itheima.net
const socketio = io('http://172.28.28.241:8003', {
// 参数
// query: {
// token: getTokens().token,
// },
// 连接方式
// withCredentials: true,
transports: ['websocket'],
rememberUpgrade: true,
});
console.log(socketio);
// socketio.on('chatevent', () => {
// console.log('接收后端服务请求');
// });
// 2 连接成功
socketio.on('connect', () => {
console.log(socketio.id);
console.log('websocket 连接成功');
// 让小智给你打个招呼
// setChatList([
// { message: '你好,我是小智', type: 'xz' },
// { message: '你有什么疑问?', type: 'xz' },
// ]);
});
// return () => {
// socketio.close();
// };
}, []);
return (
// ...
<div className="chat-list">
{chatList.map((item, index) => {
return (
<div
key={index}
className={classnames(
'chat-item',
item.type === 'xz' ? 'self' : 'user'
)}
>
{/* {item.type === 'xz' ? (
<Icon type="iconbtn_xiaozhitongxue" />
) : (
<img src="http://geek.itheima.net/images/user_head.jpg" alt="" />
)} */}
<div className="message">{item.message}</div>
</div>
);
})}
</div>
);
};
// export default Chat;
首先在引入端口后不会产生websocket 连接成功原因在于在请求的时候生成了一个sid
问题参考
总的来说前端使用的是js后端使用java产生问题正常现象,并且可以进入服务器