php与java通过socket通信demo
PHP通过socket与java进行通信与基本的sockent编程没什么区别,一个读,一个写,只是方便起见,用java写,PHP读。
demo实现的简单功能是,接受PHP端写入的字符串,然后原样返回给输出端。代码如下:
1 import java.io.*;
2 import java.net.*;
3
4 public class Server {
5 public static void main(String[] args) throws IOException{
6 System.out.println("Server started !\n");
7 ServerSocket server=new ServerSocket(5678);
8 while (true){
9 Socket client=server.accept();
10 System.out.println("client coming!\n");
11 PrintWriter printer = new PrintWriter(client.getOutputStream());
12 BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
13 String m = reader.readLine();
14 System.out.println("get infomation " + m + "\n from " + client.getInetAddress().toString());
15 printer.println(m);
16 printer.flush();
17 printer.close();
18 printer.close();
19 client.close();
20 System.out.println("client leaving!\n");
21 }
22 }
2 import java.net.*;
3
4 public class Server {
5 public static void main(String[] args) throws IOException{
6 System.out.println("Server started !\n");
7 ServerSocket server=new ServerSocket(5678);
8 while (true){
9 Socket client=server.accept();
10 System.out.println("client coming!\n");
11 PrintWriter printer = new PrintWriter(client.getOutputStream());
12 BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
13 String m = reader.readLine();
14 System.out.println("get infomation " + m + "\n from " + client.getInetAddress().toString());
15 printer.println(m);
16 printer.flush();
17 printer.close();
18 printer.close();
19 client.close();
20 System.out.println("client leaving!\n");
21 }
22 }
运行起来,以后该java程序将监听5678端口,当接收到消息以后,将接收的消息原样返回给客户端……
PHP的代码如下:
1 <?php
2 $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( 'could not create socket' );
3 $connect = socket_connect ( $socket, '127.0.0.1', 5678 );
4 //向服务端发送数据
5 socket_write ( $socket, 'Hello' . "\n" );
6 //接受服务端返回数据
7 $str = socket_read ( $socket, 1024, PHP_NORMAL_READ );
8
9 echo $str;
10 //关闭
11 socket_close($socket);
12 ?>
2 $socket = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP ) or die ( 'could not create socket' );
3 $connect = socket_connect ( $socket, '127.0.0.1', 5678 );
4 //向服务端发送数据
5 socket_write ( $socket, 'Hello' . "\n" );
6 //接受服务端返回数据
7 $str = socket_read ( $socket, 1024, PHP_NORMAL_READ );
8
9 echo $str;
10 //关闭
11 socket_close($socket);
12 ?>
PHP程序连接本机的5678端口,写入 Hello,然后读取返回的数据……将返回的数据,输出到浏览器……
原文来自:http://istrone.com/?p=832