关于socket的小问题

博客展示了 Java 中使用 Socket 实现简单服务器和客户端的代码。服务器在端口 5432 监听连接,接收连接后发送消息;客户端连接到指定地址和端口,接收并打印消息。代码包含输入输出流操作及异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import  java.net.*;  
import  java.io.*;  
 
public  class  SimpleServer  {  
       public  static  void  main(String  args[])  {  
               ServerSocket  s  =  null;  
               Socket  s1;  
               String  sendString  =  "Hello  Net  World!";  
               OutputStream  s1out;  
               DataOutputStream  dos;  
 
//  Register  your  service  on  port  5432  
               try  {  
                       s  =  new  ServerSocket(5432);  
               }  catch  (IOException  e)  {  }  
 
//  Run  the  listen/accept  loop  forever  
               while  (true)  {  
                       try  {  
//  Wait  here  and  listen  for  a  connection  
                               s1=s.accept();  
 
//  Get  a  communication  stream  for  soocket  
                               s1out  =  s1.getOutputStream();  
                               dos  =  new  DataOutputStream  (s1out);  
 
//  Send  your  string!  (UTF  provides  machine-independent  format)  
                               dos.writeUTF(sendString);  
 
//  Close  the  connection,  but  not  the  server  socket  
                               s1out.close();  
                               s1.close();  
                       }  catch  (IOException  e)  {  }  
               }  
       }  
}


package cn.pdx.gree;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

import java.net.*;
import java.io.*;

public class SimpleClient {
    public static void main(String args[]) throws IOException {
        int c;
        Socket s1;
        InputStream s1In;
        DataInputStream dis;

// Open your connection to myserver, at port 5432
        s1 = new Socket("127.0.0.1",5432);

// Get an input file handle from the socket and read the input
        s1In = s1.getInputStream();
        dis = new DataInputStream(s1In);

        String st = new String (dis.readUTF());
        System.out.println(st);

// When done, just close the connection and exit
        s1In.close();
        s1.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值