I have .net socket server , I successfuly connect to it using socket.io with angular ..but I cannot found how to send data to server and recieve from it ..can anyone help me
-
Possible duplicate of [How to use socket.io-client in angular 4](https://stackoverflow.com/questions/47161589/how-to-use-socket-io-client-in-angular-4) – Martin Schneider Apr 02 '18 at 12:06
3 Answers
Work with Observables
and write an Angular service with methods to listen
and send
messages to the server:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Message } from '../model/message';
import * as socketIo from 'socket.io-client';
const SERVER_URL = 'https://yourserverhost.com/';
@Injectable()
export class SocketService {
private socket;
public initSocket(): void {
this.socket = socketIo(SERVER_URL);
}
public send(message: Message): void {
this.socket.emit('message', message);
}
public onMessage(): Observable<Message> {
return new Observable<Message>(observer => {
this.socket.on('message', (data: Message) => observer.next(data));
});
}
}
Find a complete app using WebSockets, Node.js and Angular written entirely in TypeScript here: https://github.com/luixaviles/socket-io-typescript-chat
I hope it helps.

- 691
- 5
- 8
To send data to server you should use socket.emit() function something like this:
io.on('connection', function(socket){
socket.emit('server method', dataToSend);
});
To recieve data from server you should listen to server functions. For this purposes exists socket.on() method:
.on('connection', function(socket){
socket.on('server method', function(msg){
console.log('message: ' + msg);
});
});
You can read more about emitting and receiving data: https://socket.io/get-started/chat/
Here are some links using socket.io with angular project: https://medium.com/@vipinswarnkar1989/socket-io-in-mean-angular4-todo-app-29af9683957f https://tutorialedge.net/typescript/angular/angular-socket-io-tutorial/

- 210
- 2
- 6
-
-
-
import * as socketIo from ‘socket.io-client’; var socket = socketIo.connect(‘http://172.18.13.3:8080’) – haneen hasan Dec 21 '17 at 06:46
I needed this as well, and socket.io-client API does not fit very well in an angular app, and it should be wrapped with rxjs, IMHO.
So that's why I created a really tiny wrapper library.
https://github.com/harunurhan/rx-socket.io-client
You can use it like below:
const socket = new RxSocket('/url/to/socket.io/server');
const event$ = socket.subject('event_name'); // get rxjs/Subject for a specific event
event$.subscribe((data) => { // read data
console.log(data.foo)
});
event$.next({foo: 'bar'}); // send data
// create observables for events that you want to only listen (receive data)
const event$ = socket.observable('event_name'); // get rxjs/Observable for a specific event
event$.subscribe((data) => { // read data
console.log(data.foo)
});

- 1,516
- 1
- 17
- 21