How to send data using tcp/ip from raspberrypi to windows form
어디에서 어디를 호출할지. ^^; 그림 좀 그려보고 짜보자구
server - link link2 (enrol_method) (nonblocking_mode)
(noblocking server side code)\
- #include
- #include
- #include <sys/socket.h>
- #include
- #include <netinet/in.h>
- #include
- #include
- #define PORT 8080
- int main(int argc, char const *argv[])
- {
- int server_fd, new_socket, valread;
- struct sockaddr_in address;
- int opt = 1;
- int addrlen = sizeof(address);
- char buffer[1024] = {0};
- char *hello = ”Hello from server”;
- //Creating socket file descriptor
- if((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0 )
- {
- perror(“socket failed”);
- exit(EXIT_FAILURE);
- }
-
if(setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR SO_REUSEPORT, & opt, sizeof(opt))) - {
- perror(“setsockopt”);
- exit(EXIT_FAILURE);
- }
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(PORT);
- if(bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
- {
- perror(“bind failed”);
- exit(EXIT_FAILURE);
- }
- if(listen(server_fd, 3)< 0)
- {
- perror(“listen”);
- exit(EXIT_FAILURE);
- }
- if((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
- {
- printf(“server accept failed….\n”);
- exit(0);
- }
- int flag = fcntl(new_socket, F_GETFL, 0);
-
fcntl(new_socket, F_SETFL, flag O_NONBLOCK); - int read_size = 0;
- while(1)
- {
- read_size = read(new_socket, buffer, 1024);
- if(read_size > 0 )
- {
- printf(“%s\n”,buffer);
- write(new_socket, hello, strlen(hello));
- printf(“Hello message sent\n”);
- }
- }
- return 0;
- }
client winform c# - link
- 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 SimpleTCP;
- namespace tcp_ip_client_test
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- SimpleTcpClient client;
- private void button1_Click(object sender, EventArgs e) //connect
- {
- connectBtn.Enabled = false;
- //Connect to server
- client.Connect(ttxtHost.Text, Convert.ToInt32(txtPort.Text));
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- client = new SimpleTcpClient();
- client.StringEncoder = Encoding.UTF8;
- client.DataReceived += Client_DataReceived;
- }
- private void Client_DataReceived(object sender, SimpleTCP.Message e)
- {
- //Update message to txtStatus
- txtStatus.Invoke((MethodInvoker)delegate ()
- {
- txtStatus.Text += e.MessageString;
- });
- }
- private void button2_Click(object sender, EventArgs e) //send
- {
- client.WriteLineAndGetReply(txtMessage.Text, TimeSpan.FromSeconds(3));
- }
- }
- }