php通过socket向应用程序发数据

本文介绍了一个简单的C#服务器程序与PHP客户端通过TCP/IP进行通信的例子。服务器使用.NET框架监听8200端口并接收来自客户端的消息,而PHP客户端则连接到指定的IP地址和端口,并发送当前日期作为消息。
摘要由CSDN通过智能技术生成

server   c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Configuration;
using System.Net;

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
	    TcpListener tcpListener= new TcpListener(8200) ;
	    tcpListener.Start() ;
	    Console.WriteLine("Server Started") ;
	    Socket socketForClient ;
	    NetworkStream networkStream;        
	    StreamReader streamreader;
            
            socketForClient = tcpListener.AcceptSocket();
            networkStream = new NetworkStream(socketForClient);
            streamreader = new StreamReader(networkStream);

	    while(true)
	    {
                if (socketForClient.Connected)
                {
                    try
                    {
                        testmsg = streamreader.ReadLine();
                    }
                    catch
                    {
                        testmsg = null;
                    }

                    if (testmsg != null)
                    {
                        Console.WriteLine(testmsg);
                    }
                    else
                    {
                        streamreader.Close();
                        networkStream.Close();
                        socketForClient.Close();
                    }
                }
                else
                {
                    socketForClient = tcpListener.AcceptSocket();
                    Console.WriteLine("new client connect");
                    networkStream = new NetworkStream(socketForClient);
                    streamreader = new StreamReader(networkStream);
                }
	    }
        }
   }
}

client  php

<?php 
error_reporting(E_ALL);
set_time_limit(0);
echo "TCP/IP connection\n";
$service_port=8200;
$address="192.168.0.176";
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket<0){
	echo "create socket error\n";
}
else
{
	echo "create ok\n";
}
$result =socket_connect($socket,$address,$service_port);
if($result<0)
{ 
	echo "connect failed\n".socket_strerror(socket_last_error());
}
else
{
	echo "connect ok\n";
}
$in=date('Y-m-d');
if(!socket_write($socket,$in,strlen($in)))
{
	echo "write failed\n";
}
else
{
	echo "write success\n";
}

socket_close($socket);
echo "close ok";
?>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值