|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
诸如RMI,EJB等一些技术并不是你说的那么复杂,而是它们把一些复杂的工具封装成不复杂的工具了,理解这些工具是需要些时间。我问你,.net网页编程里有这些工具吗?要简单多少?。
收集编程中最主要的就是SOCKET,它实在也就是监听端口的道理。和我们用手机发短信的道理应当是大抵无二(我是如许了解的),而JAVA最杰出的一点也就是“无疾苦连网”。
收集最基础的精力就是让两台呆板毗连起来,“被呼唤的一方”也就是服务器,而“找人的一方”则叫做客户机,以是说在毗连中服务器、客户机也就是一个绝对的观点了。而我们对呆板的标识次要是经由过程IP地点和端口来辨别的。
“传输把持协定”TCP和“用户数据报协定”是两种分歧的协定,JAVA对这两种协定的撑持基础是分歧的,而它们自己最年夜的区分也就是发送的牢靠性和速度,前者比拟后者是牢靠协定,后者固然是速率快很多了,上面我们分离用两个SOCKET下演示:
eg1:
//Clients.java
importjava.io.*;
importjava.net.*;
publicclassClients
{
publicstaticvoidmain(String[]args)throwsException
{
InetAddressaddr=InetAddress.getByName(null);
Socketsocket=newSocket(addr,2000);
PrintWriterout=
newPrintWriter(
newBufferedWriter(
newOutputStreamWriter(
socket.getOutputStream())),true);
byte[]b=newbyte[2048];
Stringmsg=newString(b,0,System.in.read(b));
out.println(msg);
socket.close();
}
}
//Servers.java
importjava.io.*;
importjava.net.*;
publicclassServers
{
publicstaticvoidmain(String[]args)throwsException
{
ServerSockets=newServerSocket(2000);
try{
while(true){
Socketsocket=s.accept();
try{
BufferedReaderin=
newBufferedReader(
newInputStreamReader(
socket.getInputStream()));
StringBuffersb=newStringBuffer();
intc;
while((c=in.read())!=-1){
charch=(char)c;
sb.append(ch);
}
System.out.println(sb.toString());
}catch(IOExceptione){
socket.close();
}finally{
socket.close();
}
}//while
}finally{
s.close();
}//try
}//main
}
此程式次要用Servers来举行无穷监听,而Clients是客户机发送程式,他们的端口全接纳2000。
eg2:
//UDPsend.java
importjava.io.*;
importjava.net.*;
/**
*Thisclasssendsthespecifiedtextorfileasadatagramtothe
*specifiedportofthespecifiedhost.
**/
publicclassUDPSend{
publicstaticfinalStringusage=
"Usage:javaUDPSend...
"+
"or:javaUDPSend-f";
publicstaticvoidmain(Stringargs[]){
try{
//Checkthenumberofarguments
if(args.length<3)
thrownewIllegalArgumentException("Wrongnumberofargs");
//Parsethearguments
Stringhost=args[0];
intport=Integer.parseInt(args[1]);
//Figureoutthemessagetosend.
//Ifthethirdargumentis-f,thensendthecontentsofthefile
//specifiedasthefourthargument.Otherwise,concatenatethe
//thirdandallremainingargumentsandsendthat.
byte[]message;
if(args[2].equals("-f")){
Filef=newFile(args[3]);
intlen=(int)f.length();//figureouthowbigthefileis
message=newbyte[len];//createabufferbigenough
FileInputStreamin=newFileInputStream(f);
intbytes_read=0,n;
do{//loopuntilwevereaditall
n=in.read(message,bytes_read,len-bytes_read);
bytes_read+=n;
}while((bytes_read<len)&&(n!=-1));
}
else{//Otherwise,justcombinealltheremainingarguments.
Stringmsg=args[2];
for(inti=3;i<args.length;i++)msg+=""+args[i];
message=msg.getBytes();
}
//Gettheinternetaddressofthespecifiedhost
InetAddressaddress=InetAddress.getByName(host);
//Initializeadatagrampacketwithdataandaddress
DatagramPacketpacket=newDatagramPacket(message,message.length,
address,port);
//Createadatagramsocket,sendthepacketthroughit,closeit.
DatagramSocketdsocket=newDatagramSocket();
dsocket.send(packet);
dsocket.close();
}
catch(Exceptione){
System.err.println(e);
System.err.println(usage);
}
}
}
//UDPreceive.java
importjava.io.*;
importjava.net.*;
/**
*Thisprogramwaitstoreceivedatagramssentthespecifiedport.
*Whenitreceivesone,itdisplaysthesendinghostandprintsthe
*contentsofthedatagramasastring.Thenitloopsandwaitsagain.
**/
publicclassUDPReceive{
publicstaticfinalStringusage="Usage:javaUDPReceive";
publicstaticvoidmain(Stringargs[]){
try{
if(args.length!=1)
thrownewIllegalArgumentException("Wrongnumberofargs");
//Gettheportfromthecommandline
intport=Integer.parseInt(args[0]);
//Createasockettolistenontheport.
DatagramSocketdsocket=newDatagramSocket(port);
//Createabuffertoreaddatagramsinto.Ifanyonesendsusa
//packetcontainingmorethanwillfitintothisbuffer,the
//excesswillsimplybediscarded!
byte[]buffer=newbyte[2048];
//Createapackettoreceivedataintothebuffer
DatagramPacketpacket=newDatagramPacket(buffer,buffer.length);
//Nowloopforever,waitingtoreceivepacketsandprintingthem.
for(;;){
//Waittoreceiveadatagram
dsocket.receive(packet);
//Convertthecontentstoastring,anddisplaythem
Stringmsg=newString(buffer,0,packet.getLength());
System.out.println(packet.getAddress().getHostName()+
":"+msg);
//Resetthelengthofthepacketbeforereusingit.
//PriortoJava1.1,wedjustcreateanewpacketeachtime.
packet.setLength(buffer.length);
}
}
catch(Exceptione){
System.err.println(e);
System.err.println(usage);
}
}
}
在UDP中次要的类是DatagramSocket()和DatagramPacket(),而在UDPreceive中,被承受的字节是受限定,这些感到不是太好,既然buf是一个字节数组,我们其实是很奇异为何构建器本人不克不及查询拜访出数组的长度呢?独一能推测的缘故原由就是C作风的编程使然,那边的数组不克不及本人告知我们它有多年夜。
而我们实践利用的过程当中,固然不单单限于这些,个中要思索有多台客户机来毗连服务器,以是要思索到线程Thread的利用,假如再加上SWING,就能够做一个相似于QQ的SOCKET功效了,这仅仅限于我在进修SOCKET时的一些意会。供人人参考。
微软什么都提供了。你可以试想一下,如果你是新手,你是希望你点一下按钮程序就能运行那,还是想自己一点一点的组织结构,然后打包发部,调错再打包...... |
|