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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章