服務器與客戶端連接不能正常連接,偶爾能連上。
麻煩各位高手看看,程式哪里有問題。
上位機TCP服務器程式,用VB寫的使用WinSock控制元件
Private Sub Form_Load()
'將 LocalPort 屬性設定為一個整數。
'然后呼叫 Listen 方法。
TcpServer.Protocol = sckTCPProtocol
TcpServer.LocalPort = 4000
TcpServer.Listen
End Sub
Private Sub tcpServer_ConnectionRequest(ByVal requestID As Long)
'檢查控制元件的 State 屬性是否為關閉的。
'如果不是,
'在接受新的連接之前先關閉此連接。
If TcpServer.State <> sckClosed Then TcpServer.Close
'接受具有 requestID 引數的
'連接。
TcpServer.Accept requestID
End Sub
Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
'為進入的資料宣告一個變數。
'呼叫 GetData 方法,并將資料賦予名為 txtOutput
'的 TextBox 的 Text 屬性。
Dim strData As String
TcpServer.GetData strData
TxtOutput.Text = strData
End Sub
下位機使用STM32F107, TCP客戶端程式
int main(void)
{
....................
LwIP_Init();
//UDP_rx_Init();
TCP_Client_init();
....................
while(1){
................
}
}
void TCP_Client_init(void)
{
struct tcp_pcb *pcb;
struct ip_addr ipaddr;
//int localPort;
//localPort = 1000 + (int)ip_address_last;
IP4_ADDR(&ipaddr,192,168,0,2); //服務器IP192.168.0.2
pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, 1001);
tcp_connect(pcb, &ipaddr, 4000, tcp_client_connected);
}
err_t tcp_client_connected(void *arg, struct tcp_pcb *pcb, err_t err)
{
//TcpPCB = pcb;
tcp_write(pcb, GREETING, strlen(GREETING), 0); //輸出Str
tcp_recv(pcb,tcp_Receive);
return ERR_OK;
}
static err_t tcp_Receive(void *arg, struct tcp_pcb *pcb, struct pbuf *p_1, err_t err)
{
unsigned char *temp;
unsigned int i;
if(p_1 != NULL) /* 如果收到的資料不為空 */
{ rec_data_size = (*p_1).tot_len;
temp = p_1->payload;
for(i=0;i<rec_data_size;i++)
{
eth_rec_data[i] = *temp;
temp++;
}
pbuf_free(p_1); /* 釋放緩沖區資料 */
rec_ethernet_flag = 1;
}
return ERR_OK;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/148647.html
標籤:單片機/工控
