zoukankan      html  css  js  c++  java
  • javaTCP客户端和服务器的连接的简单代码(菜鸟日记)

    TCPServer.java文件中:

    import java.net.*;
    import java.io.*;
    public class TCPServer{
     public static void main(String args[]){
      InputStream in=null; OutputStream out=null;//定义输入流、输出流
      try{
       ServerSocket ss=new ServerSocket(5888); //初始化服务端
       Socket socket=ss.accept();                       //服务端和客户端相连
       in=socket.getInputStream();                     
       out=socket.getOutputStream();
       DataInputStream dis=new DataInputStream(in);             //服务器端得到客户端输入流
       DataOutputStream dos=new DataOutputStream(out);      //服务器端得到客户端输出流
       
       String s=null;
       if((s=dis.readUTF())!=null){
        System.out.println(s);
        System.out.println("from:"+socket.getInetAddress());          //获得IP地址
        System.out.println("Port:"+socket.getPort());                       //获得端口号
       }
       System.out.println(s);
       dos.writeUTF("h1,hello");
       dos.close();
       dis.close();
       socket.close();
      }catch(IOException e){
       e.printStackTrace();
      }
     }
    }

    TCPClient.java文件中:


    import java.net.*;
    import java.io.*;
    public class TCPClient{
     public static void main(String args[]){
      InputStream is=null; OutputStream os=null;
      try{
       Socket socket=new Socket("localhost",5888);                  //定义客户端的IP和端口号
       is=socket.getInputStream();                                           
       os=socket.getOutputStream();
       DataInputStream dis=new DataInputStream(is);                    //输入流
       DataOutputStream dos=new DataOutputStream(os);              //输出流
       dos.writeUTF("hey");
       String s=null;
       if((s=dis.readUTF())!=null);
       System.out.println(s);
       dos.close();
       dis.close();
       socket.close();
      }catch (UnknownHostException e){
       e.printStackTrace();
      }catch(IOException e){
       e.printStackTrace();
      }
     }
    }

    运行时先运行服务器端再运行客户端。

  • 相关阅读:
    WCF中的自定义类中包括自定义枚举类型时出错
    Asp.Net无刷新上传并裁剪头像
    C# 字符串模糊查找
    .NET中如何通过文本框中按回车键进行的提交数据
    关于Firefox、Safari 与IE区别实际应用的一点心得
    ASP.NET 网速慢时候按钮禁止重复提交
    ASP.NET前台代码绑定后台变量方法总结
    验证功能在IE中没问题,在火狐浏览器中无反应
    aspx 后台cs文件动态修改Lable 样式
    asp.net程序调试 连接池和 "Timeout expired"异常
  • 原文地址:https://www.cnblogs.com/zhangxiaomo/p/3379648.html
Copyright © 2011-2022 走看看