Support
Quality
Security
License
Reuse
Coming Soon for all Libraries!
Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Javascript library to draw and animate images, texts or SVG paths as multiple rectangular pieces
Basic usage
<!-- Canvas to draw the pieces -->
<canvas class="my-canvas"></canvas>
<script src="anime.min.js"></script>
<script src="dist/pieces.min.js"></script>
<script>
// Options for customization, see full list below
var options = {
canvas: '.my-canvas',
text: 'Some Text'
};
// Initialize a new instance, by default the pieces will be 'hidden'
var myPieces = new Pieces(options);
// Show pieces using default options. See the full list of available operations below.
myPieces.showPieces();
</script>
Operations
var options1 = {items: 0}; // Animate the first item
var options2 = {items: [0, 2]}; // Animate the first and the third items
Options to use in operations for updating pieces
// Animate everything to the "show" (`s_property`) values
const options = {
x: p => p.s_x,
y: p => p.s_y,
w: p => p.s_w,
h: p => p.s_h,
tx: p => p.s_tx,
ty: p => p.s_ty
};
myPiecesInstance.animatePieces(options);
// It's the same to call `myPiecesInstance.showPieces()` instead, just posting that here as an example
How to use select() to set a timer for sockets?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "23"
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// put the socket into non-blocking mode just for connect()
int iMode = 1;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR)
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// wait for the connect to finish
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, NULL, &fds, NULL, &timeout);
if (iResult <= 0) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
}
// put the socket back into blocking mode
iMode = 0;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
// set a read timeout
if (setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) == SOCKET_ERROR) {
printf("setsockopt failed\n");
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
/*
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, &fds, NULL, NULL, &timeout);
if (iResult <= 0) {
if (iResult == SOCKET_ERROR)
printf("select failed with error: %d\n", WSAGetLastError());
else
printf("select timed out\n");
break;
}
*/
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else if (WSAGetLastError() == WSAETIMEDOUT)
printf("recv timed out\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
Managing nested Firebase realtime DB queries with await/async
Object.keys(event.participants).forEach(async (value: any) => {
-----------------------
async function afterEventHostMail() {
// Initialize variables
events = [];
await admin.database().ref('/events_geo').once('value').then(snapshots => {
snapshots.forEach(snapshot => {
var event = snapshot.val();
var eventKey = snapshot.key;
// Do some filtering
const mergedObj = { ...event, ...{ key: eventKey } };
events.push(mergedObj)
});
});
for (const event of events) {
// Do a ton of await calls here
}
// The rest of the function
}
Why are lifetime specifiers not required [sometimes] in Rust for generics?
struct Point<T>
{
x: T,
y: T,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point
{
x: &str,
y: &str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point<'a> {
x: &'a str,
y: &'a str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point {
x: &'static str,
y: &'static str,
}
-----------------------
struct Point<T>
{
x: T,
y: T,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point
{
x: &str,
y: &str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point<'a> {
x: &'a str,
y: &'a str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point {
x: &'static str,
y: &'static str,
}
-----------------------
struct Point<T>
{
x: T,
y: T,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point
{
x: &str,
y: &str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point<'a> {
x: &'a str,
y: &'a str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point {
x: &'static str,
y: &'static str,
}
-----------------------
struct Point<T>
{
x: T,
y: T,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point
{
x: &str,
y: &str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point<'a> {
x: &'a str,
y: &'a str,
}
fn main()
{
let intro = Point{ x: "Hello", y: "World" };
}
struct Point {
x: &'static str,
y: &'static str,
}
How to pass the value of AceEditor to the component state using the onClick of a button? ReactJS
import "./styles.css";
import React, { Component } from "react";
import { makeStyles, createStyles } from "@material-ui/core/styles";
// import './CodeMirror.css';
import { Box, Button } from "@material-ui/core";
// Import Brace and the AceEditor Component
import AceEditor from "react-ace";
import TryItButton from "../CustomButton/TryItButton";
// Import a Mode (language)
import "ace-builds/src-noconflict/mode-javascript";
// Import a Theme (okadia, github, xcode etc)
import "ace-builds/src-noconflict/theme-twilight";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<CodeMirror />
dsdsd
</div>
);
}
export interface AppProps {
headings?: {
key: number;
name: string;
pathname: string;
}[];
subheadings?: {
key: number;
name: string;
calls: string[];
}[];
}
interface AppState {
value: string;
textAreaValue?: string;
}
class CodeMirror extends Component<AppProps, AppState> {
constructor(props: AppProps) {
super(props);
this.state = { value: "", textAreaValue: "" };
}
onChange(newValue: string) {
console.log("CodeMirror value: ", newValue);
this.setState({ value: newValue });
}
render() {
return (
<>
<div className="main-container-codemirror">
<div className="top-block-codemirror">
<Box className="top-bar-text-codemirror">
<i className="white">Example Call</i>
</Box>
</div>
<div className="example-block-codemirror">
<div className="textarea-example">
<AceEditor
// placeholder="Enter a call here..."
mode="javascript"
theme="twilight"
name="ace-editor"
fontSize={12}
showPrintMargin
wrapEnabled
showGutter
highlightActiveLine
value={this.state.value}
setOptions={{
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: false,
showLineNumbers: true,
tabSize: 2,
useWorker: false
}}
style={{
// position: 'relative',
width: "100%",
height: "200px"
}}
onChange={(e) => this.onChange(e)}
/>
</div>
<div className="spacer">
<Button
className="try-it-button"
onClick={() =>
this.setState((prev) => ({
...prev,
textAreaValue: prev["value"]
}))
}
style={{
backgroundColor: "#533cf8",
color: "white",
borderRadius: 0,
fontSize: 13,
fontWeight: 200
}}
>
Try it!
</Button>
<div className="spacer-text-div">
auto-update 'fat', alphabetize payload, and make the example
call below
</div>
</div>
<div className="header-2">
<i className="white">Example Response</i>
</div>
<div className="textarea-example">
<textarea
readOnly
className="example-code"
value={this.state.textAreaValue || "Response code"}
/>
</div>
<div className="bottom-block-codemirror" />
</div>
</div>
</>
);
}
}
How to call multiple components in react js and display simultaneously?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome,{DateComp} from './Welcome';
ReactDOM.render(<App/>,document.getElementById('root'));
app.js
const App = () => {
return (<div>
<Welcome/>
<Datacomp/>
</div>)
}
-----------------------
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome,{DateComp} from './Welcome';
ReactDOM.render(<App/>,document.getElementById('root'));
app.js
const App = () => {
return (<div>
<Welcome/>
<Datacomp/>
</div>)
}
-----------------------
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome, {DateComp} from './Welcome';
ReactDOM.render(<Welcome/>, document.getElementById('root1'));
ReactDOM.render(<DateComp/>, document.getElementById('root2'));
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome, {DateComp} from './Welcome';
ReactDOM.render(
<>
<Welcome/>
<DateComp/>
</>,
document.getElementById('root'),
);
-----------------------
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome, {DateComp} from './Welcome';
ReactDOM.render(<Welcome/>, document.getElementById('root1'));
ReactDOM.render(<DateComp/>, document.getElementById('root2'));
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome, {DateComp} from './Welcome';
ReactDOM.render(
<>
<Welcome/>
<DateComp/>
</>,
document.getElementById('root'),
);
Get cart items quantities from products with specific tag in WooCommerce
function action_woocommerce_before_add_to_cart_form() {
// Settings
$term = 'mix-and-match';
$taxonomy = 'product_tag';
// Box IDs. Important, these should not contain the term!
// Contents => Product ID
$box_ids = array(
4 => 1718,
9 => 1719,
16 => 1720,
20 => 1721
);
// Initialize
$total_term = 0;
$total_box = 0;
// True
if ( WC()->cart ) {
// Loop trough cart items quantities
foreach( WC()->cart->get_cart_item_quantities() as $product_id => $cart_item_quantity ) {
// Contains the definite term
if ( has_term( $term, $taxonomy, $product_id ) ) {
// Add the cart item quantity from this certain product to the counter
$total_term += $cart_item_quantity;
// The box ID is in the cart
} elseif( in_array( $product_id, $box_ids ) ) {
// Add contens * the cart item quantity to the counter
$total_box += ( array_search ( $product_id, $box_ids ) * $cart_item_quantity );
}
}
}
echo '<p>Total term: ' . $total_term . '</p>';
echo '<p>Total box = ' . $total_box . '</p>';
}
add_action( 'woocommerce_before_add_to_cart_form', 'action_woocommerce_before_add_to_cart_form', 10, 0 );
Content of my app cutting off in landscape mode
<ScrollView> *CONTENT* </ScrollView>
-----------------------
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/black">
<TextView
android:id="@+id/toptitle"
android:text="Try Our Mouthwatering Pani-Puri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:fontFamily="cursive"
android:textColor="@color/white"
/>
<ImageView
android:id="@+id/image"
android:layout_width="250dp"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:src="@drawable/panipuri"
android:layout_below="@id/toptitle"
android:layout_margin="8dp"/>
<TextView
android:id="@+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:layout_toEndOf="@id/image"
android:layout_alignParentEnd="true"
android:layout_alignTop="@id/image"
android:gravity="center"
android:text="Details"
android:textSize="20sp"
android:paddingTop="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
/>
<ImageView
android:id="@+id/icon"
android:layout_below="@id/detail"
android:layout_alignStart="@id/detail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_margin="35dp"
android:src="@drawable/ocation"/>
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/icon"
android:text="Nahar chowk, Sipahi tola, Near Durga Mandir,Purnia"
android:layout_below="@id/detail"
android:textColor="@color/white"
android:paddingTop="35sp"
android:textSize="15sp"
android:paddingRight="15dp"
android:fontFamily="monospace"/>
<ImageView
android:id="@+id/watch"
android:layout_below="@id/icon"
android:layout_alignStart="@id/detail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35sp"
android:src="@drawable/imgicon"/>
<TextView
android:id="@+id/timing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/watch"
android:text="Operates between 9 AM to 11 PM"
android:layout_below="@id/location"
android:textColor="@color/white"
android:paddingTop="35sp"
android:paddingRight="15dp"
android:textSize="15sp"
android:fontFamily="monospace"/>
<ImageView
android:id="@+id/description"
android:layout_below="@id/timing"
android:layout_alignStart="@id/detail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_margin="35sp"
android:src="@drawable/description"/>
<TextView
android:id="@+id/des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/description"
android:layout_below="@id/timing"
android:textSize="15sp"
android:textColor="@color/white"
android:paddingTop="35sp"
android:fontFamily="monospace"
android:text="Home Delivery available\nRs 10 for 8 pieces.\n"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact us:+91-6277665544 "
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="@color/white"
android:textSize="16sp"
android:layout_margin="16dp"
android:background="@color/purple_500"/>
</RelativeLayout>
Problems viewing/editing a date in php/mysql
<input name="any_name" type="date"
value="<?php echo date('Y-m-d',strtotime($data["congestart"])) ?>"/>
GoogleSheets with GoogleApps. A little loss with Creating and copying
function main() {
// get current date
var date = Utilities.formatDate(new Date(), 'UTC', 'YYYY-MM-dd');
// get current spreadsheet
var cur_ss = SpreadsheetApp.getActiveSpreadsheet();
// get folder
var folder = DriveApp.getFolderById('###'); // <--- your folder ID goes here
// get file name from the cell 'Sheet1!A1'
var name = cur_ss.getSheetByName('Sheet1').getRange('A1').getValue();
// seach for the file in the folder and get it if it exists
var file = get_file_from_folder(folder, name);
// if file exists: copy current sheet to this file
// and rename copied sheet
if (file != null) {
var dest_ss = SpreadsheetApp.openById(file.getId());
cur_ss.getActiveSheet().copyTo(dest_ss).setName(date);
}
// if file doesn't exists: make а copy of current spreadsheet,
// and rename the sheet with the same name as your active sheet
else {
var file = DriveApp.getFileById(cur_ss.getId()).makeCopy(folder).setName(name);
var dest_ss = SpreadsheetApp.openById(file.getId());
dest_ss.getSheetByName(cur_ss.getActiveSheet().getName()).setName(date);
}
}
// functions searches for the file with given name in given folder and returns the file.
// In case the folder has no such file the function returns 'null'
function get_file_from_folder(folder, name) {
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
if (file.getName() == name) return file;
}
return null;
}
JOLT to split JSON into smaller parts - update 2021/06/08
[
{
"operation": "shift",
"spec": {
"*": {
"timestamp": "[&1].timestamp",
"inverterId": "[&1].inverterId",
"systemKey": "[&1].systemKey",
"I_DC*_*": "[&1].&"
}
}
}, {
"operation": "shift",
"spec": {
"*": {
"timestamp": "[&1].timestamp",
"inverterId": "[&1].inverterId",
"systemKey": "[&1].systemKey",
"*": "[&1].keysToPivot.&"
}
}
},
{
"operation": "shift",
"spec": {
"*": {
"keysToPivot": {
"*": {
"$": "[&3].[#2].stringId",
"@": "[&3].[#2].value",
"@(2,timestamp)": "[&3].[#2].timestamp",
"@(2,inverterId)": "[&3].[#2].inverterId",
"@(2,systemKey)": "[&3].[#2].systemKey"
}
}
}
}
}
]
QUESTION
How to use select() to set a timer for sockets?
Asked 2021-Jun-15 at 21:17I'm currently using Winsock2 to be able to test a connection to multiple local telnet
servers, but if the server connection fails, the default Winsock client takes forever to timeout.
I've seen from other posts that select()
can set a timeout for the connection part, and that setsockopt()
with timeval
can timeout the receiving portion of the code, but I have no idea how to implement either. Pieces of code that I've copy/pasted from other answers always seem to fail for me.
How would I use both of these functions in the default client code? Or, if it isn't possible to use those functions in the default client code, can someone give me some pointers on how to use those functions correctly?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "23"
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo* result = NULL,
* ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
/*
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
sizeof(timeout)) < 0) {
printf("setsockopt failed\n");
}
*/
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
ANSWER
Answered 2021-Jun-15 at 21:17
select()
can set a timeout for the connection part.
Yes, but only if you put the socket into non-blocking mode before calling connect()
, so that connect()
exits immediately and then the code can use select()
to wait for the socket to report when the connect operation has finished. But the code shown is not doing that.
setsockopt()
withtimeval
can timeout the receiving portion of the code
Yes, though select()
can also be used to timeout a read operation, as well. Simply call select()
first, and then call recv()
only if select()
reports that the socket is readable (has pending data to read).
Try something like this:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "23"
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// put the socket into non-blocking mode just for connect()
int iMode = 1;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR)
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// wait for the connect to finish
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, NULL, &fds, NULL, &timeout);
if (iResult <= 0) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
}
// put the socket back into blocking mode
iMode = 0;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
// set a read timeout
if (setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) == SOCKET_ERROR) {
printf("setsockopt failed\n");
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
/*
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, &fds, NULL, NULL, &timeout);
if (iResult <= 0) {
if (iResult == SOCKET_ERROR)
printf("select failed with error: %d\n", WSAGetLastError());
else
printf("select timed out\n");
break;
}
*/
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else if (WSAGetLastError() == WSAETIMEDOUT)
printf("recv timed out\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit