0

I have been searching the internet to create a simple python 3 program which can send messages between two computers using socket. The problem I have encountered is that tutorials are python 2.

How do I create a simple messaging program using socket between two computers on a local network?

7
  • The socket interface itself has changed some... it deals in bytes not str so you need to encode and decode, but is mostly the same as ever. It should be easy to adapt most tutorials. Commented Jan 12, 2017 at 19:35
  • Smells like homework, I dunno. Commented Jan 12, 2017 at 19:37
  • This is not homework btw, I have been searching the internet for hours as a personal project. Commented Jan 12, 2017 at 19:45
  • Alternately, you could use a higher level messaging system like zeromq that "messagizes" data for you and implements several useful network patterns. Commented Jan 12, 2017 at 19:46
  • Bit of a read, but interesting: zeromq chat Commented Jan 12, 2017 at 19:50

2 Answers 2

3

I can give you a simple example, it is working in my computer, my python version is 3.4.4

The Client:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("localhost", 3333))

str_recv = s.recv(1024)

print(str(str_recv))

str_send = "Hello, the world!"

s.send(bytes(str_send, 'utf-8'))

str_recv = s.recv(1024)

print(str(str_recv))
s.close()

The Server:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('localhost', 3333))

s.listen(5)
flag = 0
while True:
    connect, addr = s.accept()
    print("Connection Address:" + str(addr))

    str_return = "Welcome to visit my test socket server. Waiting for command."
    connect.sendto(bytes(str_return, 'utf-8'), addr)

    str_recv, temp = connect.recvfrom(1024)
    print(str_recv)

    str_return = "I got your command, it is " + str(str_recv)
    connect.sendto(bytes(str_return, 'utf-8'), addr)

    connect.close()

I hope it can help you. LOL

Sign up to request clarification or add additional context in comments.

3 Comments

What is the 'b' infront of the message that is sent and how can I get rid of that? b'Welcome to visit my test socket server. Waiting for command.' b"I got your command, it is b'Hello, the world!'"
@ComputingCorn b means bytes - socket sends data as bytes. You can use data.decode('utf-8') or str(data, 'utf-8') to convert from bytes to string. And text.encode('utf-8') or bytes(text, 'utf-8') to convert string to bytes.
Yes, As @furas said!
0
        #client side software    
    
        import socket
        import threading
        import subprocess
        import tkinter
        import tkinter.scrolledtext
        from tkinter import simpledialog
        from datetime import datetime
        import emoji
        host = socket.gethostname()
        port = 49153
        
        
        class Client:
        
            def __init__(self, host, port):
                self.ke = []
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.connect((host, port))
                self.bx = 0
        
                msg = tkinter.Tk()
                msg.withdraw()
        
                self.nickname = simpledialog.askstring("Nickname", "Please enter a nickname: ", parent=msg)
        
                self.gui_done = False
                self.running = True
        
                gui_thread = threading.Thread(target=self.gui_loop)
                recieve_tread = threading.Thread(target=self.recieve)
                sd = threading.Thread(target=self.recive1)
                sd.start()
                recieve_tread.start()
                gui_thread.start()
        
            def gui_loop(self):
                self.win = tkinter.Tk()
                self.win.configure(bg="lightGray")
                self.win.title("FON CHAT")
                self.win.iconbitmap()
                # self.text_label = tkinter.Label(self.win, text="Chat: ", bg="lightgray")
                # self.text_label.config(font=("Arial", 12))
                # self.text_label.grid(padx=20, pady=5)
        
                self.text_Area = tkinter.scrolledtext.ScrolledText(self.win, font=('Arial', 20), height=15)
                self.text_Area.grid(row=0, column=0)
                self.text_Area.config(state='disabled')
        
        
        
                self.msg_label = tkinter.Label(self.win, text="Massage: ", bg="lightgray")
                self.msg_label.config(font=("Arial", 12))
                self.msg_label.grid(row=1, column=0, padx=20, pady=5)
        
        
        
                self.input_area = tkinter.Text(self.win, height=5)
                self.input_area.grid(row=2, column=0, padx=20, pady=5)
        
                massage = f'{self.nickname}'
                self.sock.send(massage.encode('utf-8'))
        
                self.send_button = tkinter.Button(self.win, text="send", command=self.write)
                self.send_button.config(font=('Arial', 12))
                self.send_button.grid(row=3, column=0)
        
                self.participantarea = tkinter.scrolledtext.ScrolledText(self.win)
        
                self.participantarea.config(width=20)
                self.participantarea.grid(row=0, column=1)
                self.participantarea.config(state='disabled')
        
                self.chat_button = tkinter.Button(self.win, text="CHAT")
                self.chat_button.grid(row=4, column=1)
        
                self.gui_done = True
                self.win.protocol("WM_DELETE_WINDOW", self.stop)
        
                self.win.mainloop()
        
        
            def write(self):
                massage = self.input_area.get(1.0, 'end-1c')
                self.sock.send(f'{datetime.now().strftime("%H:%M:%S")}, {self.nickname}&**&* {massage}'.encode('utf-8'))
                self.input_area.delete(1.0, 'end-1c')
        
            def stop(self):
                self.running = False
                self.win.destroy()
                self.sock.close()
                exit(0)
        
            def participates(self):
                connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                connection.connect((host, 9098))
                name = connection.recv(1024).decode('utf-8')
                if name != '':
                    self.participantarea.config(state='enabled')
                    self.participantarea.insert('end', name)
                    self.participantarea.yview('end')
                    self.participantarea.config(state='disabled')
        
        
        
            def recieve(self):
                while self.running:
                    try:
                        massage = self.sock.recv(1024).decode('utf-8')
                        spillitted = massage.split("&**&*")
                        if ':(' in massage:
                            ksfds = massage.find(':(')
                            k = emoji.emojize(':frowning_face:')
                            massage = str(massage).replace(':(', str(k))
        
                        elif ':)' in massage:
                            ksfds = massage.find(':)')
                            k = emoji.emojize(':grinning_face_with_big_eyes:')
                            massage = str(massage).replace(':)', str(k))
        
                        elif ':|' in massage:
                            ksfds = massage.find(':|')
                            k = emoji.emojize(':neutral_face:')
                            massage = str(massage).replace(':|', str(k))
        
                        if massage == "NICK":
                            self.sock.send(self.nickname.encode('utf-8'))
        
        
                        else:
                            if self.gui_done:
                                t = massage.replace('&**&*', '')
                                self.text_Area.config(state='normal')
                                self.text_Area.insert('end', t + '\n')
                                self.text_Area.yview('end')
                                self.text_Area.config(state='disabled')
        
                    except ConnectionAbortedError:
                        break
        
                    except:
                        print("Error")
                        self.sock.close()
                        break
        
        
            def recive1(self):
               self.sock.send(self.nickname.encode('utf-8'))
               while self.running:
        
                    try:
                        self.massage12 = self.sock.recv(1024).decode('utf-8')
                        self.splited = self.massage12.split('&**&*')
        
                        if self.splited[1] not in self.ke:
                            self.participantarea.config(state='normal')
                            self.participantarea.insert('end', self.splited[1] + '\n')
                            self.text_Area.yview('end')
                            self.participantarea.config(state='disabled')
                            self.ke.append(self.splited[1])
        
                        if self.gui_done:
                            t = self.massage12.replace('&**&*', '')
                            self.text_Area.config(state='normal')
                            self.text_Area.insert('end', t + '\n')
                            self.text_Area.yview('end')
                            self.text_Area.config(state='disabled')
                        else:
                            pass
        
                    except IndexError:
                        pass
        
        
        
        tread = threading.Thread(target=Client, args=(host, port))
        tread.start()

#server side software
import socket
import threading


host = socket.gethostname()
port = 49153


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen()

s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s2.bind((host, 60001))
s2.listen()

clients = []
nicknames = []

fclients = []
fnicknames = []




def broadcast(massage):
    for client in clients:
        client.send(massage)




def handle(client):
    while True:
        try:

            # now = datetime.now().time().strftime("%H:%M:%S")  # time object
            # date = datetime.now().strftime("%Y-%m-%d")  # date object
            massage = client.recv(1024)
            # massage = f'[{date}] {now}: {massage}'
            broadcast(massage)



        except:
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            nicknames.remove(nickname)
            break


def recieve():
    while True:
        client, address = s.accept()
        print(F"Connected with {address}, {client}")
        # client.send("NICKNAME?".encode('utf-8'))
        nickname = client.recv(1024)
        nicknames.append(nickname)
        print(f'{client} + {nickname} + {address}')
        broadcast(f"{nickname} connected with server \n".encode('utf-8'))
        # client.send("connected to server".encode('utf-8'))
        clients.append(client)
        thread = threading.Thread(target=handle, args=(client, ))
        thread.start()



print("server is running")
recieve()

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.