java socket 简单的服务端与客户端通讯

import java.net.*;
import java.io.*;
import java.lang.Integer;
 
public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      //serverSocket.setSoTimeout(10000);
   }
 
   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
            //阻塞等待客户端链接
            Socket server = serverSocket.accept();
            System.out.println("远程主机地址:" + server.getRemoteSocketAddress());

            //初始化输入输出流,获取客户端发送的数据
            DataInputStream in = new DataInputStream(server.getInputStream());
            //打印客户端发送的数据
            System.out.println(in.readUTF());

            String ttt = new String(in.readUTF());

            //初始化输入流
            DataOutputStream out = new DataOutputStream(server.getOutputStream());

            //向客户机发送消息
            out.writeUTF(ttt);

            //关闭套接字
            server.close();
         }catch(SocketTimeoutException s)
         {
            //超时退出
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            //错误信息
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      

      int port = Integer.parseInt("9991");
      try
      {
         Thread t = new GreetingServer(port);
         t.run();
      }catch(IOException e)
      {
         e.printStackTrace();

      }
   }
}

 

客户端列子

// 文件名 GreetingClient.java
 
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
     //定义链接的地址和端口号
      String serverName = "127.0.0.1";
      int port = Integer.parseInt("9991");
      try
      {
        
        //链接到服务器
         System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
         Socket client = new Socket(serverName, port);

         //获取远程主机地址和端口号:
         System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
         //初始化客户端输出流
         OutputStream outToServer = client.getOutputStream();
         //初始化客户端发送输出流
         DataOutputStream out = new DataOutputStream(outToServer);
 
        //客户机发送信息给服务端
         out.writeUTF("我是来自客户端1的信息,收到请回答");

         //初始化服务端输入流
         InputStream inFromServer = client.getInputStream();
         //获取服务端响应输入流
         DataInputStream in = new DataInputStream(inFromServer);

        //打印服务端返回信息
         System.out.println("服务器响应: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
      }
   }
   

 

posted @ 2021-07-15 14:42  神迹丶  阅读(207)  评论(0编辑  收藏  举报
网站已运行: