课程实验1 基于java Socket的C/S小程序

前言

网路程序设计这课完全是基于java的,而本人java学的很渣...再加上没有网络编程经验,学起来真是苦啊...所以励志这两个月好好攻一下java,至少要把基础掌握牢!

    这系列博客,算是我的学习体会和经验吧,其中肯定会有一些错误,当然我也会在发现错误及时纠正的~如果得幸,有神牛看了我的文章,挑出了我的问题,请不要吝惜的给我指出来~非常感谢~


了解的知识点

这次我做的是一个客户机-服务器模型的基于java套接字的,小的发送字符串的程序,总结一下学到的东西~

  1.Java Socket的编程步骤:

客户机:(1)连接服务器,获取Socket

       (2)通过Socket得到输入输出流

       (3)(这里很重要)通过三层封装输入、输出流,得到BufferedReader和BufferedWriter的对象,用封装后的对象去发送或者接收字符串~

       (4)一定注意结束后关闭输入输出流和Socket,而且一定后关Socket

服务器:(1)创建ServerSocket

       (2)阻塞等待客户端连入

(3)连入后,拿到一个和客户端通信的Socket,开启一个线程去和客户端交流

(4)主线程继续阻塞等待,交流线程后续类似客户机

2.Java方面的小知识(详细的会另写文章讲,这里概述一下)

(1)输入输出流要封装三次,才能正常的用String等(这里今后再细学)

(2)一些方法会抛出异常,这些方法外一定要try...catch,或者让主函数继续抛出异常

(3)finally接在catch,即是不管有没有异常,一定会执行的块

(4)继承Thread是在类不是其它类的子类时的方法,重载run方法去做你要做的事。用Thread.Start,启动线程,它会调用run方法

(5)向外发出数据时,要flush一下,否则数据在缓冲区里根本没出去....

代码

客户端

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;
import java.io.*;
import java.net.*;

/**
 *
 * @author luke28
 */
public class Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try{
            Socket soc = null;
            InputStream is = null;
            OutputStream os = null;
            try {
                soc = new Socket("192.168.1.2",8000);
                System.out.println("连接中...");
                is = soc.getInputStream();
                os = soc.getOutputStream();
                System.out.println("服务器端地址:"+soc.getInetAddress()+"\n端口号:"+soc.getPort());
            
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
                System.out.println("收到:"+new String(in.readLine()));
                //系统输入内容
                in = new BufferedReader(new InputStreamReader(System.in));
                String msg = null;
                do{
                    msg = in.readLine();
                    out.write(msg + "\r\n");
                    out.flush();
                }while(!msg.equals("quit"));
                System.out.println("对话结束.");
            }catch(Exception e){
                System.out.println("出错:"+e);
            }finally{                           //进入了catch之后还会进入finally执行
                is.close();os.close();soc.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

未实现多客户端的服务器

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server1;
import java.net.*;
import java.io.*;

/**
 *
 * @author luke28
 */
public class Server1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try{           
             ServerSocket svr = null;
             Socket soc = null;
             InputStream is = null;
             OutputStream os = null;
             try{
                svr = new ServerSocket(8000);
                while(true){
                    soc = svr.accept();
                    is = soc.getInputStream();
                    os = soc.getOutputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(is));
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
                    System.out.println("客户端地址:" + soc.getInetAddress()+"\n客户端端口号:"+soc.getPort());
                    out.write(new String("欢迎连接~!...\r\n"));
                    out.flush();
                    String msg = null;
                    do{
                         msg = in.readLine();
                         System.out.println("收到:" + msg);
                     }while(!msg.equals("quit"));
                    System.out.println("客户已断开~");
                    is.close();os.close();soc.close();
                }
           }catch(Exception e){
               System.out.println("出错:"+e);
           }finally{
                 svr.close();
             }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


实现多客户端的服务器

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server2;
import java.net.*;
import java.io.*;
/**
 *
 * @author luke28
 */

class MyThread extends Thread{
    Socket soc = null;
    int id = 0;
    public MyThread(Socket soc,int id){
        this.soc = soc;
        this.id = id;
    }
    @Override
    public void run(){
        InputStream is = null;
        OutputStream os = null;
        try{
             is = soc.getInputStream();
             os = soc.getOutputStream();
            System.out.println("一个新的客户端连接~\n编号为"+id+"\n客户端地址:"+
                    soc.getInetAddress()+"客户端端口号:"+soc.getPort());
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            out.write(new String("欢迎连接~\r\n"));
            out.flush();
            String msg = null;
            do{
                msg = in.readLine();
                System.out.println("编号为"+id+"的客户端发来:"+msg);
            }while(msg.equals("quit") == false);
            System.out.println("编号为"+id+"的客户端断开~");
            is.close();
            os.close();
            soc.close();
        }catch(Exception e){
            System.out.println("错误:"+e);
        }
    }
}


public class Server2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ServerSocket svr = null;
        Socket sct = null;
        try{
            //抛出异常的方法
            svr = new ServerSocket(8000);
            int num = 1;
            while(true){
                try{
                    //抛出异常的方法
                    sct = svr.accept();
                    
                }catch(IOException e){
                    System.out.println("错误:"+e);
                    break;

                }
                MyThread myTrd =  new MyThread(sct,num++);
                myTrd.start();
            }
        }catch(Exception e){
            System.out.println("错误:"+e);
        }finally
        {
            try{
                //抛出异常的方法
                svr.close();
            }catch(Exception e){
                System.out.println("错误:"+e);
            }
        }
        
    }
}


                    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值