Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
biswa
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#include <iostream> #include <string> #include <WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") using namespace std; void main() { string ipAddress = "127.0.0.1"; // IP Address of the server int port = 54000; // Listening port # on the server // Initialize WinSock WSAData data; WORD ver = MAKEWORD(2, 2); int wsResult = WSAStartup(ver, &data); if (wsResult != 0) { cerr << "Can't start Winsock, Err #" << wsResult << endl; return; } // Create socket SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == INVALID_SOCKET) { cerr << "Can't create socket, Err #" << WSAGetLastError() << endl; WSACleanup(); return; } // Fill in a hint structure sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(port); inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr); // Connect to server int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint)); if (connResult == SOCKET_ERROR) { cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl; closesocket(sock); WSACleanup(); return; } // Do-while loop to send and receive data char buf[4096]; string userInput; do { // Prompt the user for some text cout << "> "; getline(cin, userInput); if (userInput.size() > 0) // Make sure the user has typed in something { // Send the text int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0); if (sendResult != SOCKET_ERROR) { // Wait for response ZeroMemory(buf, 4096); int bytesReceived = recv(sock, buf, 4096, 0); if (bytesReceived > 0) { // Echo response to console cout << "SERVER> " << string(buf, 0, bytesReceived) << endl; } } } } while (userInput.size() > 0); // Gracefully close down everything closesocket(sock); WSACleanup(); }
Show compiler warnings
[
+
]
Show input
edit mode
|
history
|
discussion