php与java通过socket通信的实现代码
程序员文章站
2023-11-11 19:10:46
demo实现的简单功能是,接受php端写入的字符串,然后原样返回给输出端。代码如下:
复制代码 代码如下:import java.io.*; import java.ne...
demo实现的简单功能是,接受php端写入的字符串,然后原样返回给输出端。代码如下:
复制代码 代码如下:
import java.io.*;
import java.net.*;
public class server {
public static void main(string[] args) throws ioexception{
system.out.println("server started !\n");
serversocket server=new serversocket(5678);
while (true){
socket client=server.accept();
system.out.println("client coming!\n");
printwriter printer = new printwriter(client.getoutputstream());
bufferedreader reader = new bufferedreader(new inputstreamreader(client.getinputstream()));
string m = reader.readline();
system.out.println("get infomation " + m + "\n from " + client.getinetaddress().tostring());
printer.println(m);
printer.flush();
printer.close();
printer.close();
client.close();
system.out.println("client leaving!\n");
}
}
}
运行起来,以后该java程序将监听5678端口,当接收到消息以后,将接收的消息原样返回给客户端……
php的代码如下:
复制代码 代码如下:
<?php
$socket = socket_create ( af_inet, sock_stream, sol_tcp ) or die ( 'could not create socket' );
$connect = socket_connect ( $socket, '127.0.0.1', 5678 );
//向服务端发送数据
socket_write ( $socket, 'hello' . "\n" );
//接受服务端返回数据
$str = socket_read ( $socket, 1024, php_normal_read );
echo $str;
//关闭
socket_close($socket);
php程序连接本机的5678端口,写入 hello,然后读取返回的数据……将返回的数据,输出到浏览器……
先运行起java的服务端,然后用浏览器访问php页面,将看到从服务器端返回的hello