phpsocket

$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
if($socket == FALSE)
{
	echo "创建socket失败";
	return;
}

$tmp = socket_connect($socket, '127.0.0.1', '1234');
if($tmp == FALSE)
{
	echo socket_last_error($socket);
	return;
}

$tmp = socket_write($socket, "Hello PHP");
if($tmp == FALSE)
{
	echo socket_last_error($socket);
	return;
}

$tmp = socket_read($socket, 256);
if($tmp == "")
{
	echo "error ".socket_last_error($socket);
	return;
}
echo "接收: ".$tmp;

做了一个java的服务端

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

public class MyServer
{
	ServerSocket serverSocket = null;
	Socket socket = null;
	Timer timer = null;

	public static void main(String[] args)
	{
		new MyServer();
		new Thread(new Runnable()
			{
				public void run()
				{
					while(true)
					{
						try
						{
							Thread.sleep(1000);
						}catch(InterruptedException ie)
						{
						}
					}
				}
			}).start();
	}

	public MyServer()
	{
		try
		{
			serverSocket = new ServerSocket(1234);
		}catch(IOException ioe)
		{
			System.out.println(ioe.toString());
			return;
		}

		timer = new Timer("MyServer", true);
		timer.schedule(new TimerTask()
			{
				public void run()
				{
					System.out.println("等待连接");
					try
					{
						socket = serverSocket.accept();
						new MySocket(socket);
					}catch(IOException ioe)
					{
					}
				}
			}, 
			100,
			200);
		
	}
	
}

 

import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class MySocket
{
	Socket socket = null;;
	InputStream inputStream = null;
	OutputStream outputStream = null;
	Timer timer = null;
	
	public MySocket(Socket arg)
	{
		socket = arg;
		try
		{
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
		}catch(IOException ioe)
		{
			System.out.println(ioe.toString());
			return;
		}
		

		timer = new Timer("Socket", true);
		timer.schedule(new TimerTask()
			{
				public void run()
				{
					int count = 0;
					try
					{
						count = inputStream.available();
					}catch(IOException ioe)
					{
						System.out.println("bye");
					}
					if(count != 0)
					{
						byte tmp[] = new byte[count];
						try
						{
							inputStream.read(tmp);
							System.out.println(new String(tmp));
							outputStream.write("Hello Java".getBytes());
						}catch(IOException ioe)
						{
							timer.cancel();
						}
					}
				}
			}, 100, 200);
	}
}

<a herf="http://jilu.xcgmym.com">我的小站</a>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值