Java Socket 应用例子

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

public class EchoServer
{
     public static void main(String[] args)
     {
         try{
             ServerSocket s = new ServerSocket(2536);
             Socket incoming = s.accept();
             BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
             PrintWriter out = new PrintWriter(incoming.getOutputStream(), true /* autoFlush */);
             out.println("Hello! Enter BYE to exit.");
             boolean done = false;
             while (!done)
             {
                 String line = in.readLine();
                 if (line == null)
                     done = true;
                 else{
                     out.println("Echo: " + line);
                     if (line.trim().equals("BYE"))
                         done = true;
                 }
             }
             incoming.close();
         }
         catch (Exception e){
             System.out.println(e);
         }
     }

}


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

public class EchoClient {

     public static void main(String args[]) {
         try {
             if (args.length != 1) {
                 System.out.println("USAGE: java Client servername");
                 return;
             }
             String connectto = args[0];
             Socket connection;
             if (connectto.equals("localhost")) {
                 connection = new Socket(InetAddress.getLocalHost(), 2536);
             }
             else {
                 connection = new Socket(InetAddress.getByName(connectto), 2536);
             }
             BufferedReader input = new BufferedReader(new InputStreamReader(
                     connection.getInputStream()));

             PrintWriter out = new PrintWriter(connection.getOutputStream(),true );
             String info;
             info = input.readLine();
             System.out.println(info);
             boolean done = false;
             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
             String sInput;
             while (!done) {
                 sInput = in.readLine();
                 out.println(sInput);
                 if (sInput.equalsIgnoreCase("bye"))
                     done = true;
                 info = input.readLine();
                 System.out.println(info);
             }
             connection.close();
         }
         catch (SecurityException e) {
             System.out.println("SecurityException when connecting Server!");
         }
         catch (IOException e) {
             System.out.println("IOException when connecting Server!");
         }
     }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值