Socket编程—Client、Server通信

来源:互联网 发布:windows字体文件下载 编辑:程序博客网 时间:2024/06/11 10:24

编写TCP通信程序,服务器端发送字符串到客户端。

ReadClient.java

//ReadClient.javaimport java.io.*;import java.net.*;public class ReadClient {public static void main(String args[]) throws IOException {Socket clientSocket = null;DataOutputStream outbound = null;DataInputStream inbound = null;InputStreamReader inS = null;try {// 与服务器建立连接clientSocket = new Socket("10.10.49.47", 80); // IP地址:10.10.49.47System.out.println("Client1: " + clientSocket);// 初始化流对象outbound = new DataOutputStream(clientSocket.getOutputStream());inbound = new DataInputStream(clientSocket.getInputStream());inS = new InputStreamReader(inbound);// 发送数据outbound.writeBytes("hello\r\n");System.out.println("hello"); // 客户端输出"hello"字符串outbound.flush();int c;while ((c = inS.read()) != -1) {System.out.print((char) c);}} catch (UnknownHostException uhe) {System.out.println("UnknownHostException: " + uhe);}catch (IOException ioe) {System.err.println("IOException: " + ioe);} finally {// 关闭流及clientSocketinS.close();outbound.close();inbound.close();clientSocket.close();}}}


SimpleWebServer.java

//SimpleWebServer.javaimport java.io.*;import java.net.*;public class SimpleWebServer {public static void main(String args[]) {ServerSocket serverSocket = null;Socket clientSocket = null;int connects = 0;try {// 创建服务器Socket,端口80,限制5个连接serverSocket = new ServerSocket(80, 5);while (connects < 5) {// 等待连接clientSocket = serverSocket.accept();// 操作连接ServiceClient(clientSocket);connects++;}serverSocket.close();}catch (IOException ioe) {System.out.println("Errorin SimpleWebServer: " + ioe);}}public static void ServiceClient(Socket client) throws IOException {DataInputStream inbound = null;DataOutputStream outbound = null;try {// 获取输入输出流inbound = new DataInputStream(client.getInputStream());outbound = new DataOutputStream(client.getOutputStream());StringBuffer buffer = new StringBuffer("\"http://www.ytu.edu.cn/\"\r\n");String inputLine;while ((inputLine = inbound.readLine()) != null) {// 判断输入为Hello时,输出字符串if (inputLine.equals("hello")) {outbound.writeBytes(buffer.toString());break;}}} finally {// 打印清除连接,关闭流及SocketSystem.out.println("Cleaningup connection: " + client);outbound.close();inbound.close();client.close();}}}


运行结果:

注意:

    Address already in use: JVM_Bind  错误  为端口冲突,改变Socket端口直到成功;

     变量声明在try外面,main函数里面,否则finally关闭流及Socket 时会出现  变量cannot be resolved     错误;

    Unhandled exception type IOException  错误为  未抛出异常,main函数发现错误抛出即可。

 

0 0
原创粉丝点击