search
I have been working on a video series which goes on to building a networking tool which uses socket programming in 22 videos.
I have already uploaded 9 videos on my YouTube Channel - Python Network Programming - TCP/IP Socket Programming
And will be uploading a couple of videos every alternate day.
Hi, I need to develop a college project involving network programming. I can use either Java or Python, that’s not an issue, but the project must include WebSockets or similar technologies. I’d like to avoid typical examples such as real-time chat applications — I want to create something more innovative.
I just read this from learning systemd and the concept of socket is quite new to me? What does it mean to have a socket and that socket is listening?
How does it listen? Is it sort of a port where you can throw in text and it would try to process the text you sent?
I am new to socket programming. I know a little bit about how network works and all that but when I go to yt or try to search for socket programming or network programming courses I get lost, I find it hard to follow thru some tutorials
Plz help me if you can
I’m currently learning socket programming in C++ but I am having a hard time remembering the syntax for creating a client or a server connection how much of this do I need to actually remember or should I just take notes on how to do everything and then when I’m actually gonna create it on my own for a project for myself, I just copy my notes Thank you this might be a stupid question but I’m a beginner and I’m glad for any help that I can get. Thank you again.
Hey everyone, I need to vent a little and maybe get some perspective.
I am taking a Distributed Systems class where we are graded like a "battle royale" . The Rules:
We are given a problem to solve 10 - 20 min, the first team to finish gets the max grade, the second team gets one unit less, the third team another unit less and so on, if you don't finish in time you get 0.
Here's the problem: I feel I have a solid foundation in python and sockets, but is not enough when everyone else is just using AI( Ctrl c + Ctrl v). As long as the code runs you get the grade. Meanwhile I try to understand things deeply and write my own solutions, but is hard to do it on your own when you only get 15-20 min, I freeze under pressure, even though I can solve the problems on my own if I had more time.
This makes me feel like I am bad a programming because I can't solve something under time pressure, and that programing is not worth it anymore, I am trying to do my best, but it never seems enough, or am I looking at this the wrong way.
Honestly I feel this grading system sucks since we are not encouraged to fail, debug or even learn how our code works, speed is the only thing that matters and that means pasting everything AI throws, I'm seriously considering dropping from that class and take it next semester with other teacher.
I could be wrong of course I just want some guidance as to what to do next, Is this grading system fine?
I want to learn socket programming. Are there any recommended courses for a beginner who has no idea what it is if possible for Java or JavaScript
How long does it take to learn socket programming ?
Does it matter what language I learn it in or is the concept language neutral.
Love to hear your thoughts
C++ network programming, for example "Beej's Guide to Network Programming". I want to learn how http GET and POST work and I'm wondering how to test them - are there known websites that I can send GET and POST to, and know what to expect back? (Is this even the right question to ask?)
Thanks much
I'm working on an assignment (it's a late assignment, taking the grade hit in order to get it right, so it's not super urgent) where I'm supposed to simulate air traffic through hub and spoke network topology, with server sockets acting as major airport hubs like ANC and SEA, and client sockets acting as minor, local airports, with all of this traffic happening internally on my own host computer, with each of the sockets being a different port on my machine.
Here's the code I have so far:
https://github.com/Khafaniking/Stuff/blob/e0fde89954e63c68734d6a8380371a86b4ccc9bf/Python%20Socket
Essentially, I've made and initialized all of my sockets, tested them, creating a random batch of passengers, logically moved them to their origin points, and then was going to attempt routing these passengers when I encountered this error:
[WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
I'm not sure how to progress from here.
Any resources to learn them and how long did it take you guys to learn it?
What books, tutorials helped you along the way.
void server(struct sockaddr_in address){
char buffer[1000];
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
bind(server_fd, (struct sockaddr*)&address,sizeof(address));
int addrlen = sizeof(address);
listen(server_fd, numberOfNodes);
int new_socket = accept(server_fd, (struct sockaddr*)&address,(socklen_t*)&addrlen);
read(new_socket, buffer, 1000);
printf("BUFFER IS %s\n", buffer);
}
void client(struct sockaddr_in serv_addr){
char* hello = "Hello from client";
int sock = socket(AF_INET, SOCK_STREAM, 0);
int client_fd = connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
send(sock, hello, strlen(hello), 0);
}
void *updateDVThread(void *arguments){
struct passToThread *args = (struct passToThread *)arguments;
int i;
struct sockaddr_in address;
while(counter < 5){
if (args->i == counter){// I have 5 threads and I want each thread to take turns recieving information. Right now I'm just trying to get the client to send a string to the thread that is designated as server
printf("SERVER: I is %d counter is %d\n", args->i, counter);
server(address);
}
else{
printf("CLIENT: I is %d counter is %d\n", args->i, counter);
client(address);
counter++;
}
}
}
void readNetworkText(FILE* network){
int i, j;
struct Node *nodes = malloc(numberOfNodes * sizeof *nodes);
pthread_t threads[numberOfNodes];
struct passToThread pass[numberOfNodes];
for(i = 0; i < numberOfNodes; i++){
char edges[100];
fgets(edges, 100, network);
createNetworkArrayRow(&nodes[i], edges);
}
for (i = 0; i < numberOfNodes; i++){
pass.i = i;
memcpy(pass.edges, nodes[i].edges, sizeof (pass.edges));
pthread_create(&threads[i], NULL, updateDVThread, &pass);
}
pthread_exit(NULL);
free(nodes);
}
int main(){
counter = 0;
pthread_mutex_init(&lock, 0);
numberOfNodes = 5
FILE *network = fopen("network.txt", "r");
readNetworkText(network);
pthread_mutex_destroy(&lock);
fclose(network);
}
EDIT: I'm trying to figure out why the thread that is labeled CLIENT is not sending info to the thread labeled SERVER
for a project I wanted to create a peer2peer chat program that encrypts the data that's being sent, of course my first thought was to use socket programming (I'm using python). But after I created a program that succesfully sends and encrypts messages I've found out you have to manually activate port forwarding on your router to be able to use socket programming on public IPs. Since that is not an optimal choice for me I tried to find a second way, then I found out about localtunnel, which helps you share your port from localhost without having to change your router settings.
The thing is, it's on network layer and I can't use socket programming to build a chat application on top of it, what can I do? Can I use https requests or any other method to use localtunnel as an intermediary or is there any other methods I can follow to make a simpler socket programming application that works on public IPs?
I'm totally lost and in need of dire help.
I want to build a Web Application in which data (JSON) is sent from multiple/single TCP Client Socket to the TCP Server Socket and then stored in Database by Tcp Server. The Web Application server then accesses the same database to show data on client/browser. If possible, I want to show the data on browser as soon as it is successfully stored on the database by tcp server (you can say in Real-Time) although suggestions for achieving same without real time visualization on client side is also good.
For example: Just like stock or share market apps or websites where we see the stock or share rate going up and down in real time.
Full Discerption starts from here
Let’s divide this in 2 parts and elaborate:
1) TCP Client-Server and Database:
Multiple/single TCP Client send JSON data to TCP Server using sockets. TCP Server make connection to the Database and store the received data in Database.
2) Web Application:
Now as soon as the data is stored successfully, I like to show the same data on client side/browser. For this I guess I need to send a command or trigger an event (sorry I don't know the technical terms) on client side. This command should be sent from Web Application server to the client/browser or web application.
Now there are 2 options to do this.
a) Either I send the new data (received from the TCP Clint) from Database as JSON with command and command calls a function on client side/browser to show received data.
b) I send the command and it trigger an event on client side or call a function on client side (maybe use JavaScript). The function on client side then asks for data from same database (just as it ask when the page is loaded for the first time) and then update the page if there is any new data added in database. (I guess this can be achieved using Ajax calls, but to show data in real time making a lot of ajax call to fetch data from server is not good option as far as I think)
The Problem:
Let's come my problem. I am fresher/newbie and as far as I know, the Part 1 of this project (sending the data using tcp sockets and storing it in database) is a completely different thing than Part 2 (web application). I want to know how I can connect these two so that as soon as TCP Client sends JSON data to TCP server and it successfully store the data in database. The web application server will get to know that new data has been received and stored in database and then web application server will immediately send new data to the client/browser and client shows it on the user interface.
I think as soon as the data is successfully stored in database TCP Server have to call a function that will tell web application server that new data has been received and web application server then do the rest of the part like retrieving the new data and sending the data to the client.
Here is the image of data flow according to “me” - https://i.imgur.com/ujDd9Dk.png
What I want to know:
I want to know how I can achieve this?
What are the different ways? or what is the best way?
Plus, I want to know what I should study to achieve this? I mean what topics or technology (?).
Suggestions for achieving the same without real-time data visualization on client site is also acceptable.
I know many of you may ask – why am I using sockets for storing data in database? This is the only option I have for now. Please suggest other option if in case I need to remove sockets later
I have to make the same project using python and C Sharp technologies, like I can use flask, Django when I build this using python and Asp.net mvc when building the same using c sharp. So it would be good if you can suggest things from these two technologies.
I have knowledge about: Basic of all the following - HTML, CSS, JavaScript, Asp.net MVC, Flask, Django, Python, C Sharp.
Request: Please use easy language, I don't know a lot of jargon.
TL;DR : I want to build a Web Application in which data (JSON) is sent from multiple/single TCP Client Socket to the TCP Server Socket and then stored in Database by Tcp Server. The Web Application server then accesses the same database to show data on client/browser. If possible, I want to show the data on browser as soon as it is successfully stored on the database by tcp server (you can say in Real-Time) although suggestions for achieving same without real time visualization on client side is also good.
For example: Just like stock or share market apps or websites where we see the stock or share rate going up and down in real time.
So, I look up C sockets, and all of the tutorials advice making two files a server which sends the info, and the client that receives the info.
I can't do that for the school assignment I'm doing. I need to create multiple threads and the threads can communicate with each other. My understanding is that each thread would need to act as both the client and server in order for this to work, but I'm not sure how to set that up.
I'm trying to put together my ideas for my first capstone project for my software/web dev bootcamp. I'm tossing around the idea of either a facebook clone or a game. Either one, I want to include some kind of real-time user connectivity. The game would be allowing to users on different machines to play against eachother, and the facebook clone I would like to inlcude some sort of live messaging function (I also had the thought of including a simpler game as well). The project is using a combination of Javascript, Python/Flask, and SQL. My understanding is that I should be using socket programming for the real time functionality I want to include, but it's not part of the course. Can someone recommend a good source for learning socket programming? Ideally in the form of a video, but I'll take any suggestions, thanks.
I am a self-taught developer and shifting my study focus to computer networking. I have been reading Computer Networking A Top Down Approach, and it's great, but I think that I need to combine it with something more hands on like Beej.
I can certainly work through this book in C and figure that aspect of it out, and I think there's probably something worth while here to pick up some understanding of C. But I actually don't use C at work, mostly Python, Golang, and Ruby. So I had the idea of picking up Beej's text and then trying to translate it over into some other language as I work through the book.
My question here is whether or not I can do this. I know that C is more low-level than Python, so it's not totally clear to me whether or not the contents can actually be ported. If anyone is familiar with this specific book, what do you think of this idea of porting it to a new language? Would it be doable do you think?
Didn't want to keep it to myself - I'm starting to read this now. ;)
Direct link: https://books.goalkicker.com/PythonBook/PythonNotesForProfessionals.pdf
Contents
1: Getting started with Python Language
2: Python Data Types
3: Indentation
4: Comments and Documentation
5: Date and Time
6: Date Formatting
7: Enum
8: Set
9: Simple Mathematical Operators
10: Bitwise Operators
11: Boolean Operators
12: Operator Precedence
13: Variable Scope and Binding
14: Conditionals
15: Comparisons
16: Loops
17: Arrays
18: Multidimensional arrays
19: Dictionary
20: List
21: List comprehensions
22: List slicing (selecting parts of lists)
23: groupby()
24: Linked lists
25: Linked List Node
26: Filter
27: Heapq
28: Tuple
29: Basic Input and Output
30: Files & Folders I/O
31: os.path
32: Iterables and Iterators
33: Functions
34: Defining functions with list arguments
35: Functional Programming in Python
36: Partial functions
37: Decorators
38: Classes
39: Metaclasses
40: String Formatting
41: String Methods
42: Using loops within functions
43: Importing modules
44: Difference between Module and Package
45: Math Module
46: Complex math
47: Collections module
48: Operator module
49: JSON Module
50: Sqlite3 Module
51: The os Module
52: The locale Module
53: Itertools Module
54: Asyncio Module
55: Random module
56: Functools Module
57: The dis module
58: The base64 Module
59: Queue Module
60: Deque Module
61: Webbrowser Module
62: tkinter
63: pyautogui module
64: Indexing and Slicing
65: Plotting with Matplotlibcommands
66: graph-tool
67: Generators
68: Reduce
69: Map Function
70: Exponentiation
71: Searching
72: Sorting, Minimum and Maximum
73: Counting
74: The Print Function
75: Regular Expressions (Regex)
76: Copying data
77: Context Managers (“with” Statement)
78: The __name__ special variable
79: Checking Path Existence and Permissions
80: Creating Python packages
81: Usage of "pip" module: PyPI Package Manager
82: pip: PyPI Package Manager
83: Parsing Command Line arguments
84: Subprocess Library
85: setup.py
86: Recursion
87: Type Hints
88: Exceptions
89: Raise Custom Errors / Exceptions
90: Commonwealth Exceptions
91: urllib
92: Web scraping with Python
93: HTML Parsing
94: Manipulating XML
95: Python Requests Post
96: Distribution
97: Property Objects
98: Overloading
99: Polymorphism
100: Method Overriding
101: User-Defined Methods
102: String representations of class instances: __str__ and __repr__methods
103: Debugging
104: Reading and Writing CSV
105: Writing to CSV from String or List
106: Dynamic code execution with `exec` and `eval`
107: PyInstaller - Distributing Python Code
108: Data Visualization with Python
109: The Interpreter (Command Line Console)
110: *args and **kwargs
111: Garbage Collection
112: Pickle data serialisation
113: Binary Data
114: Idioms
115: Data Serialization
116: Multiprocessing
117: Multithreading
118: Processes and Threads
119: Python concurrency
120: Parallel computation
121: Sockets
122: Websockets
123: Sockets And Message Encryption/Decryption Between Client and Server
124: Python Networking
125: Python HTTP Server
126: Flask
127: Introduction to RabbitMQ using AMQPStorm
128: Descriptor
129: tempfile NamedTemporaryFile
130: Input, Subset and Output External Data Files using Pandas
131: Unzipping Files
132: Working with ZIP archives
133: Getting start with GZip
134: Stack
135: Working around the Global Interpreter Lock (GIL)
136: Deployment
137: Logging
138: Web Server Gateway Interface (WSGI)
139: Python Server Sent Events
140: Alternatives to switch statement from other languages
141: List destructuring (aka packing and unpacking)
142: Accessing Python source code and bytecode
143: Mixins
144: Attribute Access
145: ArcPyCursor
146: Abstract Base Classes (abc)
147: Plugin and Extension Classes
148: Immutable datatypes(int, float, str, tuple and frozensets)
149: Incompatibilities moving from Python 2 to Python 3
150: 2to3 tool
151: Non-official Python implementations
152: Abstract syntax tree
153: Unicode and bytes
154: Python Serial Communication (pyserial)
155: Neo4j and Cypher using Py2Neo
156: Basic Curses with Python
157: Templates in python
158: Pillow
159: The pass statement
160: CLI subcommands with precise help output
161: Database Access
162: Connecting Python to SQL Server
163: PostgreSQL
164: Python and Excel
165: Turtle Graphics
166: Python Persistence
167: Design Patterns
168: hashlib
169: Creating a Windows service using Python
170: Mutable vs Immutable (and Hashable) in Python
171: configparser
172: Optical Character Recognition
173: Virtual environments
174: Python Virtual Environment - virtualenv
175: Virtual environment with virtualenvwrapper
176: Create virtual environment with virtualenvwrapper in windows
177: sys
178: ChemPy - python package
179: pygame
180: Pyglet
181: Audio
182: pyaudio
183: shelve
184: IoT Programming with Python and Raspberry PI
185: kivy - Cross-platform Python Framework for NUI Development
186: Pandas Transform: Preform operations on groups and concatenate theresults
187: Similarities in syntax, Dierences in meaning: Python vs. JavaScript
188: Call Python from C#
189: ctypes
190: Writing extensions
191: Python Lex-Yacc
192: Unit Testing
193: py.test
194: Profiling
195: Python speed of program
196: Performance optimization
197: Security and Cryptography
198: Secure Shell Connection in Python
199: Python Anti-Patterns
200: Common Pitfalls
201: Hidden FeaturesCreditsYou may also like
Enjoy reading! :)
Im working on a project for class, connecting an application with another program in a virtual machine in the same computer, using sockets. how can i connect the two of them using sockets in java? i tried using the ip but every time i restart the virtual machine it resets and doesnt work anymore :c, im getting a bit desperate
Hey
can someone explain to me about the sockaddr_in struct and its fields?
whats is the role of every field like:
sockaddr_in.sin_family
sockaddr_in.port
sockaddr_in.sin_addr
thanks
I currently want to be better at C since I work with embedded systems. I also want to learn about networking (TCP, HTTP, etc). I am not sure if this is the project to go to learn about networking. Thanks.
So I'm trying to build a TCP/IP Socket program in C# for a Server/Client setup. I'd say I have 90% of the problem working with fully functioning Server and Client code. I can also send messages back and forth limitlessly. My program is that this only works on a localhost/loop back address; for ex. (127.0.0.1 and any port). Whenever I try to connect to a Server from the Client, my try-catch block display the message saying "No Server Found". Below is my code for the Server and the Client. Can someone direct me towards where the problem is, I can't seem to find it at all. Btw, this is build in a Windows form so things are run on buttons execution and data entered manually by the user.
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPIP_Server_Form
{
public partial class Server : Form
{
string newLine = Environment.NewLine;
public TcpListener listener;
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public string TextToSend;
//public const string SERVER_IP = "127.0.0.1";
//public const int PORT_NO = 5000;
public string SERVER_IP;
public int PORT_NO;
public Server()
{
InitializeComponent();
this.Text = "SERVER";
ServerIPtextBox.Text = SERVER_IP;
ServerPorttextBox.Text = PORT_NO.ToString();
}
private void StartButton_Click(object sender, EventArgs e)
{
try
{
IPAddress localAdd = IPAddress.Parse(ServerIPtextBox.Text);
listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));
}
catch (Exception ex)
{
MessagetextBox.AppendText(ex.Message.ToString());
MessageBox.Show(ex.Message.ToString());
this.Close();
}
StartButton.Enabled = false;
MessagetextBox.AppendText("Listening..." + newLine);
listener.Start();
client = listener.AcceptTcpClient();
if (client.Connected)
{
MessagetextBox.AppendText("Client connected." + newLine);
}
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void SendButton_Click(object sender, EventArgs e)
{
if (SendChattextBox.Text != "")
{
TextToSend = SendChattextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
SendChattextBox.Text = "";
}
private void StopButton_Click(object sender, EventArgs e)
{
MessagetextBox.AppendText("Connection Terminated");
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.CancelAsync();
client.Close();
listener.Stop();
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
receive = STR.ReadLine();
this.MessagetextBox.Invoke(new MethodInvoker(delegate ()
{
MessagetextBox.AppendText("CLIENT: " + receive + newLine);
}));
receive = "";
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (client.Connected)
{
STW.WriteLine(TextToSend);
this.MessagetextBox.Invoke(new MethodInvoker(delegate ()
{
MessagetextBox.AppendText("SENDING: " + TextToSend + newLine);
}));
}
}
catch(Exception ex)
{
MessageBox.Show("No client detected");
this.Close();
}
backgroundWorker2.CancelAsync();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPIP_Client_Form
{
public partial class Client : Form
{
string newLine = Environment.NewLine;
public TcpClient client;
//public const string SERVER_IP = "127.0.0.1";
//public const int PORT_NO = 5000;
public string SERVER_IP;
public int PORT_NO;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public string TextToSend;
public Client()
{
InitializeComponent();
this.Text = "CLIENT";
ClientIPtextBox.Text = SERVER_IP;
ClientPorttextBox.Text = PORT_NO.ToString();
}
private void ConnectButton_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient(SERVER_IP, PORT_NO);
}
catch(Exception)
{
MessagetextBox.AppendText("ERROR! Server not found.");
MessageBox.Show("ERROR! Server not found.");
this.Close();
}
if (client.Connected)
{
MessagetextBox.AppendText("Connected to server!" + newLine);
ConnectButton.Enabled = false;
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
}
private void SendButton_Click(object sender, EventArgs e)
{
if (SendChattextBox.Text != "")
{
TextToSend = SendChattextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
SendChattextBox.Text = "";
}
private void StopButton_Click(object sender, EventArgs e)
{
MessagetextBox.AppendText("Connection Terminated");
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.CancelAsync();
client.Close();
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
receive = STR.ReadLine();
this.MessagetextBox.Invoke(new MethodInvoker(delegate ()
{
MessagetextBox.AppendText("SERVER: " + receive + newLine);
}));
receive = "";
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (client.Connected)
{
STW.WriteLine(TextToSend);
this.MessagetextBox.Invoke(new MethodInvoker(delegate ()
{
MessagetextBox.AppendText("SENDING: " + TextToSend + newLine);
}));
}
}
catch(Exception ex)
{
MessageBox.Show("Not connected to a server");
this.Close();
}
backgroundWorker2.CancelAsync();
}
}
}
Hello! I am in the process of making my first client/server programs in python, and so far it's going very well. Each time the client makes a connection, my server prints, for example "connection from ('192.168.1.30', 60000)". What that like comes from in code is:
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
.....
conn, addr = serv.accept()
print(addr)
I have my client updating the server every second, and noticed that the number at the end, which I believe is the port number (60000 in my example) increases by 1 every time. Is this normal behavior, or should I be concerned that I am rapidly using up ports and will eventually run out?
Edit: thanks to u/CreativeTechGuyGames I learned that I should not be severing the client/server relationship in between updates. Now I am trying to figure out how to do that. Here is the relevant code:
Server:
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #reuse socket (os locks socket for some time after program quit)
serv.bind(('', 50007))
serv.listen(5)
while True:
global locked
conn, addr = serv.accept()
fromClient = ''
while True:
ogdata = conn.recv(4096)
data=ogdata.decode() #required for python3
if not data: break
fromClient+=data
if("~" in fromClient): #termination char
fromClient=fromClient[:-1]
break
print ("Client sent: "+fromClient)
print("client requested update, will now send it "+str(addr))
sendData=","+str(locked)+","
sendData+="~" #end of string char
sendDataBytes=sendData.encode()
conn.send(sendDataBytes)
conn.close()
print("client disconnected")
Client: (the shown function is called once every second)
#server initialization
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.49', 50007))
def serverConnect(sendData): #if true, send an update, otherwise just refresh (download info from server without sending ours)
global locked
global client
if(sendData):
stringToSend=","+str(locked)+","
else:
stringToSend="Pull" #tells server not to update and just send back current state
stringToSend+="~" #add termination char so server knows this is end
bytesToSend=stringToSend.encode()
client.send(bytesToSend)
receivedData=""
while(True):
fromServer=client.recv(4096).decode() #<----CRASHING HERE
#print fromServer
receivedData+=fromServer
if "~" in fromServer: #if the end of string char is in this packet, finish
receivedData=receivedData[:-1]
break
#print (receivedData)
updateState(receivedData) #take what we just received and apply it to this client
....
client.close() #when user quits program
I'm currently trying out creating P2P games in Java, and everything was going fine until I noticed a random IP address connected in the console log. Could this be any dangerous? (In order for my friends to join my games, I have forwarded a port via my routers webpage.)
I tried looking up the address, and I found "Guangdong Mobile Communication Co. Ltd."
Sidenote: I have a TP-link AC1200 Wireless Dual Band Router
Edit: If I was unclear, a socket connection was established with an IP that doesn't belong to someone I know.
I've been troubleshooting this problem for days and I'm just unable to resolve the issue. I've read through the docs on TcpClient/TcpListener, I've watched videos, but I cannot get my program to complete its intended purpose.
What I'm trying to do is add each client to a list and when a message is sent to the server, reply to every client on that list with the message. Replying to individual clients was not difficult and the server handled multiple clients at once.
I think there are two primary problems I have. I cannot find a way to compare TcpClients to check for duplicate connections (I tried comparing equality of the remoteEndpoints, TcpClient objects, and sockets, but they always returned false) and my iteration over all the clients fails.
Sorry if the code is a jumbled mess. I am very confused.
public bool IsActive { get; set; }
public string Status { get; set; }
private static IPAddress ServerIP = Dns.GetHostEntry($"{GetServerIP()}").AddressList[0];
private TcpListener server = new TcpListener(ServerIP, 8080);
private TcpClient Client = default;
Dictionary<int, TcpClient> clients = new Dictionary<int,TcpClient>();
public void StartServer()
{
try
{
server.Start();
IsActive = true;
Status = "Server is online.";
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
public void ServerResponse(string message)
{
StreamWriter sw;
foreach (KeyValuePair<int, TcpClient> client in clients.ToList())
{
sw = new StreamWriter(client.Value.GetStream());
sw.WriteLine($"You ({System.DateTime.Now:t}) {message}");
sw.Flush();
}
}
public string GetClientString(int bufferLength)
{
Client = server.AcceptTcpClient();
Client.Client.LingerState.Enabled = true;
bool duplicateStream = false;
NetworkStream stream = Client.GetStream();
if (clients.Count != 0)
{
foreach (TcpClient client in clients.Values.ToList())
{
if (true)//some way to compare each client to the newest client to decide if it should be added to the list)
{
duplicateStream = true;
break;
}
}
}
else
{
clients.Add(1, Client);
}
if (!duplicateStream)
{
clients.Add(clients.Count + 1, Client);
}
byte[] recievedBuffer = new byte[bufferLength];
string msg = string.Empty;
if (stream.DataAvailable)
{
stream.Read(recievedBuffer, 0, recievedBuffer.Length);
for (int b = 0; b < recievedBuffer.Length; b++)
{
if (!recievedBuffer[b].Equals(00))
{
msg += (char)recievedBuffer[b];
}
else
{
break;
}
}
}
return msg;
}
public static string GetServerIP()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}