▶ 이번 포스팅은 C#과 Python을 이용한 간단한 Socket 통신입니다.
장비 업계 실무 간, 상위 보고 또는 RDP - FTP를 몇 번 진행한 적이 있었는데, 아무래도 연차가 별로 안되서
처음부터 끝까지 다 짜보진 않았지만, 통신에 대한 기본을 다지기 위해 공부하다가
C#과 Python을 이용한 간단한 통신 방식을 코드로 구현해봤습니다.
(StackOverFlow, Youtube 참고...)
-. 상위 보고 종류들??
ex) Pattern Matching %, Blob Score, Align X-Y Gap, Laser Cutting Gap 등...
-. RDP - FTP
ex) Image(Pattern Search, Blob 검출 Area, 특정 구간 Capture), Log Data(Align Value, Blob Detection Pixel, File Path...)
Python / Server
import socket, threading
def binder(client_socket, addr):
print('Connected by', addr)
try:
while True:
# 4byte socket...
data = client_socket.recv(4)
# c# bitconverter, Big-endian - 최초 4byte recv size
length = int.from_bytes(data, "big")
# 4byte - endian 길이 만큼 recv
data = client_socket.recv(length)
# recv data string 변환
msg = data.decode()
print('Received from', addr, msg)
msg = "echo : " + msg
# byte 형식으로 변환
data = msg.encode()
length = len(data)
# Big-endian type로 convertor 후, byte 변환
client_socket.sendall(length.to_bytes(4, byteorder='big'))
# data to client send
client_socket.sendall(data)
except:
print("except : " , addr)
finally:
client_socket.close()
# Socket Create
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# local ip
server_socket.bind(('', 9999))
# Server Lis
server_socket.listen()
try:
# 1:n, 무한 루프
while True:
client_socket, addr = server_socket.accept()
th = threading.Thread(target=binder, args = (client_socket,addr))
th.start()
except:
print("server")
finally:
server_socket.close()
C# / Client
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Project
{
class Program
{
static void Main(string[] args)
{
// C# Client
// Socket Create
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999));
var data = Encoding.UTF8.GetBytes("message from c# Language");
client.Send(BitConverter.GetBytes(data.Length));
client.Send(data);
// 4byte Read
data = new byte[4];
// data receive
client.Receive(data, data.Length, SocketFlags.None);
// server(bit endian) → client(little endian) 전송되어 Reverse
Array.Reverse(data);
data = new byte[BitConverter.ToInt32(data, 0)];
client.Receive(data, data.Length, SocketFlags.None);
Console.WriteLine(Encoding.UTF8.GetString(data));
}
Console.WriteLine("Press any key...");
Console.ReadLine();
}
}
}
▶ Server - Client Data 통신에서 big-endian과 little-endian 방식이 나오는 데, 아래 링크 참고 하시면 도움 되실 거
같습니다.
참조 : genesis8님의 tistory
https://genesis8.tistory.com/37
리틀 엔디안 VS 빅 엔디안
먼저 둘을 비교하기에 앞서 엔디언이란 무엇인가? 엔디언(Endianness)은 컴퓨터의 메모리와 같은 1차원의 공간에 여러 개의 연속된 대상을 배열하는 방법을 뜻하며, 바이트를 배열하는 방법을 특히
genesis8.tistory.com
'Language - C# > C#(문법)' 카테고리의 다른 글
| C# - Dubug Logging (0) | 2021.12.01 |
|---|---|
| C# - Enum 열거형 LINQ 사용 (0) | 2021.11.25 |
| C# - Visual Studio Python 연동 - 2 (0) | 2021.11.10 |
| C# - Visual Studio Python 연동 - 1 (0) | 2021.11.10 |
| C# - Effective C# 개정판, 매개 변수 (0) | 2021.11.08 |