使用java建立基于socket的c/s接收系统 socketipportjavac/s
程序员文章站
2022-05-15 22:38:26
...
//运行时输入端口 import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; public class TCPEchoServer { /** * @param args */ private static final int BUFSIZE = 32; public static void main(String[] args) throws IOException { if (args.length != 1)//获取启动服务的端口 throw new IllegalArgumentException("Parameter(s): <Port>"); int servPort = Integer.parseInt(args[0]); //分配一个端口用于启动server端 ServerSocket servSock = new ServerSocket(servPort); int recvMsgSize; byte[] receiveBuf = new byte[BUFSIZE]; while (1) { Socket clntSock = servSock.accept(); //接收客户端的主动连接 SocketAddress clientAddress = clntSock.getRemoteSocketAddress(); System.out.println("Handling client at " + clientAddress); InputStream in = clntSock.getInputStream(); OutputStream out = clntSock.getOutputStream(); while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } clntSock.close(); } } }
运行java TCPEchoServer 8001
8001为端口号
//运行时输入 连接地址 字符 端口 import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; public class TCPEchoClient { public static void main(String[] args) throws IOException { if ((args.length < 2) || (args.length > 3)) // 传入的数据在2~3之间,0:地址 1:传输字符 <2:端口> throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]"); String server = args[0]; // ip地址或主机名称 byte[] data = args[1].getBytes(); int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;//默认端口为7 Socket socket = new Socket(server, servPort); System.out.println("Connected to server...sending echo string"); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(data); int totalBytesRcvd = 0; int bytesRcvd; while (totalBytesRcvd < data.length) { if ((bytesRcvd = in.read(data, totalBytesRcvd,data.length - totalBytesRcvd)) == -1) throw new SocketException("Connection closed prematurely"); totalBytesRcvd += bytesRcvd; } System.out.println("Received: " + new String(data)); socket.close(); } }
运行java TCPEchoClient 172.0.0.1 "quan" 8001
172.0.0.1为启动服务的ip
"quan"为传输的字符
8001为启动服务的端口
在cs系统中client连接server需要sap<ip:port>