Java socket服务端

本文主要讲解java socket服务端通信内容,服务端监听客户端,并且获取客户端的消息。

监听的主要代码是一个while死循环,因为需要实现持续监听。读者可重点阅读MySocketServer

类的代码。详细代码如下:

package com.test;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class MySocketServer {
   private int port;
   ServerSocket soc = null;
   Socket client = null;
   
   public MySocketServer(int port){
       super();
       try {
        soc = new ServerSocket(port);
        //soc.setSoTimeout(10000);
    } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    }
   }
   
   //给客户端发送消息
   public void sendDataToClient(String msg){
      if (client == null){
          System.out.println("当前无客户端连接");
          return;
      }
      
      try {
        OutputStream out = client.getOutputStream();
        out.write(msg.getBytes());
    } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    }
       
   }
   
   public void recDataFromClient(){
       while (true){
           try {
            if ( (client = soc.accept()) != null ) {                
                recDataFromClient(client); 
               }
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
       }
   }   
   
   public void recDataFromClient(Socket AClient){
          byte[] b=null;
          StringBuilder rec = null;      
        try {
                String ip= "来自主机"+AClient.getRemoteSocketAddress() + "的消息:";
                InputStream in = AClient.getInputStream();                    
                b = new byte[1024];                
                int len= 0 ;
                while ( (len=in.read(b))!=-1){
                    String strText= new String(b,0,len);                    
                    writeDataToTxt(strText);
                }            
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
       }
   
   public void writeDataToTxt(String strText){
       String fileName = "msg.txt";
       File f = new File(fileName);
       FileOutputStream out = null;
       try {
          out = new FileOutputStream(f,f.exists());
          if (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();
        }
    }
   }
   
}

 

package com.test;

import java.util.Scanner;

public class ServerSocketDemo {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
         int port = 8080;
         MySocketServer server = new MySocketServer(port);
         System.out.println("Socket服务端已启动,端口号是:"+port);
         Thread t1 = new Thread(new Runnable(){
         
            @Override
            public void run() {
                // TODO 自动生成的方法存根
                server.recDataFromClient();
            }
             
         });
         
         Thread t2 = new Thread(new Runnable(){

            @Override
            public void run() {
                // TODO 自动生成的方法存根
                while (true){
                    Scanner sc= new Scanner(System.in);
                    String st = sc.nextLine();//获取输入信息
                    server.sendDataToClient(st);
                }
            }
             
         });
         t1.start();       //接收客户端的消息
         t2.start();     //给客户端发送消息
         
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值