Java socket客户端

本文介绍了一个Java Socket客户端的实现,详细展示了如何通过Socket类建立与服务器的连接,发送消息并接收服务器响应的过程。代码中包含了创建Socket实例、发送消息到服务器以及接收服务器返回消息的具体步骤。

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

java socket客户端与服务端通信源码

package com.main;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class MySocketClient {
  private Socket soc = null;
  private String server = "";
  private int port = 0;
  
  public MySocketClient(String server,int port){
    super(); 
    this.server = server;
    this.port=port;
    try {
        soc = new Socket(server,port);
    } catch (Exception e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    } 
  }
  
  //给服务器发送消息
  public void sendMsgToServer(String msg){
     try {
        OutputStream out = soc.getOutputStream();
        out.write(msg.getBytes());
    } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    }  
  }
  
  //从服务器接收消息
  public void recMsgFromServer(){
     byte[] b= null;
     StringBuilder text = null;
     while (true){
         try {
            InputStream in = soc.getInputStream();
            b = new byte[1024];
            int len=0;
            while ( (len=in.read(b))!=-1){
                String strText = new String(b,0,len);
                System.out.println(strText);
                writeDataToTxt(strText);
            }
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
     }
  }
  
  public void writeDataToTxt(String strText){
       String fileName = "E:\\Desktop\\Temp\\01.txt";
       File f = new File(fileName);
       FileOutputStream out = null;
       try {
          out = new FileOutputStream(f,f.exists());
          strText = "\n" + strText;
          out.write(strText.getBytes());
          out.close();          
    } catch (Exception e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
        try {
            out.close();
        } catch (IOException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }
    }
  }
  
  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值