获取ServerSocket对象,new出来构造参数:int类型端口号
调用ServerSocket对象的accept()方法,得到Socket对象
获取PrintWriter对象,new出来,构造参数:OutputSream对象,true自动刷新
调用PrintWriter对象的println()方法,打印文本,参数:String对象
调用Socket对象的close()方法
调用ServerSocket对象的close()方法
import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketDemo { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ServerSocket ss=new ServerSocket(10002); System.out.println("正在监听10001..."); Socket socket=ss.accept(); PrintWriter pw=new PrintWriter(socket.getOutputStream(), true); pw.println("<h1>Hello ServerSocket</h1>"); socket.close(); ss.close(); } }
windows系统有个远程登陆的工具telnet,默认没有开启,进入控制面板==>启用关闭windows功能里,勾选一下
PHP版:
调用socket_create()方法,创建socket对象,参数:AF_INET(ipv4协议),SOCK_STREAM(字节流),SOL_TCP(TCP协议)
调用socket_bind()方法,绑定socket,参数:socket对象,ip地址,端口
调用socket_listen()方法,监听socket,参数:socket对象
调用socket_accept()方法,接收资源,参数:socket对象
调用socket_write()方法,打印信息,参数:资源,文本信息
调用socket_close()方法,关闭socket,参数:socket对象
<?php $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP); socket_bind($socket,"127.0.0.1",10003); socket_listen($socket); $resource=socket_accept($socket); $msg="<h1>Hello PHP ServerSocket</h1>"; write($resource,$msg,strlen($msg)); socket_close($socket);
client.php
<?php header("Content-type:text/html;Charset=UTF-8"); $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); //创建一个socket socket_connect($socket,'127.0.0.1',10003); //连接socket socket_write($socket,"2,ni hao,wo shi client1!"); //向socket中写入发送给服务器的数据 $data = socket_read($socket,1024); //读取socket中服务器回复的数据 echo $data; //将读取到的数据打印出来 //socket_close($socket);
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/12662.html