Topic: Socket网络编程-TCP/UDP(初学者可进)

  Print this page

1.Socket网络编程-TCP/UDP(初学者可进) Copy to clipboard
Posted by: 水之后
Posted on: 2008-08-28 20:35

   在JBuilder里设置运行参数,也就是设置主函数main(String[]args)里面的args参数:
   点击运行的绿色小三角图标旁边的下拉菜单,选择“configurations”,然后在弹出窗口中点击“new”,写入“Name”,通过“MainClass”选择主要的类,在“ApplicationParameters”中写入参数,即给应用程序传递参数。
   在Eclispe中:点击“Run”菜单,选择“OpenRunDialog...”,在弹出窗口中设定“Name”、“MainClass”,然后点击“(X)=Arguments”就可以设定Programargemuents了。
   写入运行参数后,点击相应绿色运行箭头的下拉菜单选择相应的运行条件就可以运行了。
   在一些编程当中,比如,在下面的Socket编程中,方法Server()与方法Client都在同一个类SocketC里,要进行测试的时候,就要根据参数来配置两个运行条件,然后分别运行就可以测试了

  ************************************************************
基于TCP的

  
  importjava.io.*;
  importjava.net.*;
  
  publicclassSocketC{
  
   publicstaticvoidServer(){
   ?try{
   ??ServerSocketss=newServerSocket(6000);
   ??Sockets=ss.accept();
   ??InputStreamin=s.getInputStream();
   ??OutputStreamout=s.getOutputStream();
   ??byte[]buff=newbyte[100];
  
   ??//输入流往字节数组buff写入数据,并且返回写入的字节数组的长度
   ??//相当于以下两行
   ??//in.read(buff);
   ??//intlen=buff.length;
   ??intlen=in.read(buff);
   ??System.out.println(newString(buff,0,len));
  
   ??//下面的Client方法中用的是一个字节数组来接受输入流读进来的字节型数据,
   ??//所以这里也要通过getBytes()方法转换成字节型
   ??//此为,getBytes("GBK2312")这样的方式还可以制定字节的编码类型
   ??out.write("hello".getBytes());
   ??out.close();
   ??in.close();
   ??s.close();
   ??ss.close();
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ?}
   }
  
   publicstaticvoidClient(){
   ?try{
   ??//对本地IP的获取有三种方法:InetAddress.getByName("localhost")
   ??//InetAddress.getByName("127.0.0.1"),InetAddress.getByName("null"),
   ??//当然引号内也可以直接写IP地址
   ??Sockets=newSocket(InetAddress.getByName("localhost"),6000);
  
   ??InputStreamin=s.getInputStream();
   ??OutputStreamout=s.getOutputStream();
   ??byte[]buff=newbyte[100];
   ??intlen=in.read(buff);
   ??System.out.println(newString(buff,0,len));
   ??out.write("Thisisifwater!".getBytes());
   ??out.close();
   ??in.close();
   ??s.close();
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ?}
   }
   publicstaticvoidmain(Stringargs[]){
   ?//这里的参数长度就是通过最上面的方法进行配置的
   ?if(args.length>0){
   ??Server();
   ?}else{
   ??Client();
   ?}
   ??
   }
  }
  
  ***********************************************************
  
  上面的程序中。服务器端只为一个客户端服务,即只能接受一个客户端的通信。下面,通过改造,为每个客户端创造一个线程,实现服务端可以接受多个客户端的请求。
  importjava.io.*;
  importjava.net.*;
  
  publicclassSocketCextendsThread{
   privateSockets;
  
   //在构造方法里面。this.s是指上面定以的private变量s
   //=后面的s是参数传进去的s
   //构造方法的初始化类的作用,使得类SocketC接收一个Socket类型的对象s
   publicSocketC(Sockets){
   ?this.s=s;
   }
   publicvoidrun(){
   ?try{
   ??//在run方法中,通过Socket套接字s去去获取输出流和输入流,
   ??//从而与客户端进行通信
   ??InputStreamin=s.getInputStream();
   ??OutputStreamout=s.getOutputStream();
   ??byte[]by=newbyte[100];
   ??intlen=in.read(by);
   ??System.out.println(newString(by,0,len));
   ??out.write("hello".getBytes());
   ??out.close();
   ??in.close();
   ??s.close();
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ??}
   }
   publicstaticvoidServer(){
   ?try{
   ??ServerSocketss=newServerSocket(6000);
   ??while(true){
   ???
   ??//一个服务器端的套接字等待客户端的请求消息
   ??//一但有请求进来,就返回一个Socket套接字s
   ??//即由服务套接字ServerSocket对象接受客户端请求后返回客户段套接字Socket对象
   ??Sockets=ss.accept();
   ??
   ??//通过构造方法的参数将建立连接后的Socket的s传递到类SocketC里
   ??//SocketC是线程类,通过线程的start()方法,调用执行run()方法
   ??//newSocketCMoon.start();相当于下面两行代码
   ??//SocketCsc=newSocketCMoon;
   ??//sc.start();
   ??newSocketCMoon.start();
   ??}
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ?}
   }
  
  
   publicstaticvoidClient(){
   ?try{
   ??Socketsk=newSocket(InetAddress.getByName("127.0.0.l1"),6000);
   ??InputStreamin=sk.getInputStream();
   ??OutputStreamout=sk.getOutputStream();
   ??byte[]buff=newbyte[100];
   ??intlen=in.read(buff);
   ??System.out.println(newString(buff,0,len));
   ??out.write("Thisisifwater!".getBytes());
   ??out.close();
   ??in.close();
   ??sk.close();
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ?}
   }
   publicstaticvoidmain(Stringargs[]){
   ?if(args.length>0)
   ??Server();
   ?else
   ??Client();
   }
  }
  *************************************************************
  
  在下面的部分,服务端增加带缓冲区的功能。
  
   publicvoidrun(){
   ?try{
   ??InputStreamin=s.getInputStream();
   ??OutputStreamout=s.getOutputStream();
   ??//构造带缓冲的输入流
   ??BufferedOutputStreambos=newBufferedOutputStream(out);
   ??byte[]by=newbyte[100];
   ??intlen=in.read(by);
   ??System.out.println(newString(by,0,len));
   ??bos.write("hello".getBytes());
   ??//在缓冲区数据没有写满的时候,写出数据
   ??//如果用了close()方法,则不必要用flush()方法
   ??//bos.flush();
   ??bos.close();
   ??
   ??in.close();
   ??s.close();
   ?}catch(Exceptionex){
   ??ex.printStackTrace();
   ??}
   }

************************************************************
基于UDP的


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

public class SocketC extends Thread{

//基于UDP的接收端(服务器端)
public static void recy(){
try{
//先建立一个接收端的DatagramSocket套接字ds,并帮定端口号
DatagramSocket ds=new DatagramSocket(6000);
//定以一个数据包DatagramPacket用于接受数据,这个数据包由一个字节数组构造
byte[] buff=new byte[100];
DatagramPacket dp=new DatagramPaket(buff,100);

//套接字对象接收数据包中的数据
ds.receive(dp);

//String(byte[] bytes, int offset, int length)
//Constructs a new String by decoding the specified subarray
//of bytes using the platform's default charset
system.out.println(new String(buff,0,dp.getLength()));

ds.cloese();
}catch(Exception ex){
ex.printStackTrace()
}
}
  
public static void send(){
try{
//建立发送端(客户端)的套接字,用来发送数据
DatagramSocket ds=new DatagramSocket();
//打包要发送的数据
String str="Hello";
DatagramPacket dp=new DatagramPaket(str.getBytes(),str.length,InetAddress.getByName("localhost"),6000);
//通过套接字的send方法发送数据包,并关闭
ds.send(dp);

//发送端接受数据,并打印
byte[] buff=new byte[100];
DatagramPacket dpReciv=new DatapramPacket(buff,100);
ds.receive(dpReciv);
System.out.println(new String(buff,0,dpReciv.getLength()));
ds.close();
}catch(Exception ex){
ex.printStackTrace();
}
}

  
  public static void main(String args[]){
    if (args.length>0)
      recy();
    else
      send();
  }
}


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923