服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

谈谈tcp和udp的一些简单应用

  网络编程中最重要的就是socket,它其实也就是监听端口的原理。和我们用手机发短信的原理应该是大致无二(我是这样理解的),而java最出色的一点也就是“无痛苦连网”。

  网络最基本的精神就是让两台机器连接起来,“被呼叫的一方”也就是服务器,而“找人的一方”则叫做客户机,所以说在连接中服务器、客户机也就是一个相对的概念了。而我们对机器的标识主要是通过ip地址和端口来区分的。

  “传输控制协议”tcp和“用户数据报协议”是两种不同的协议,java对这两种协议的支持基本是一致的,而它们本身最大的区别也就是发送的可靠性和速率,前者相比后者是可靠协议,后者当然是速度快得多了,下面我们分别用两个socket下演示:

eg1:

//clients.java

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


public class clients
{
public static void main(string[] args) throws exception
{
inetaddress addr = inetaddress.getbyname(null);
socket socket = new socket(addr,2000);
printwriter out =
new printwriter(
new bufferedwriter(
new outputstreamwriter(
socket.getoutputstream())),true);
byte[] b = new byte[2048];
string msg = new string(b,0,system.in.read(b));
out.println(msg);
socket.close();
}
}


//servers.java


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

public class servers
{
public static void main(string[] args) throws exception
{
serversocket s = new serversocket(2000);
try{
while(true){
socket socket = s.accept();
try{
bufferedreader in =
new bufferedreader(
new inputstreamreader(
socket.getinputstream()));
stringbuffer sb = new stringbuffer();
int c;
while( (c = in.read()) != -1 ){
char ch = (char)c;
sb.append(ch);
}
system.out.println(sb.tostring());

}catch(ioexception e){
socket.close();
}finally{
socket.close();
}
}//while
}finally{
s.close();
}//try
}//main
}


此程式主要用servers来进行无限监听,而clients是客户机发送程式,他们的端口全采用2000。


eg2:

//udpsend.java
import java.io.*;
import java.net.*;

/**
* this class sends the specified text or file as a datagram to the
* specified port of the specified host.
**/
public class udpsend {
public static final string usage =
"usage: java udpsend .../n" +
" or: java udpsend -f ";

public static void main(string args[]) {
try {
// check the number of arguments
if (args.length < 3)
throw new illegalargumentexception("wrong number of args");

// parse the arguments
string host = args[0];
int port = integer.parseint(args[1]);

// figure out the message to send.
// if the third argument is -f, then send the contents of the file
// specified as the fourth argument. otherwise, concatenate the
// third and all remaining arguments and send that.
byte[] message;
if (args[2].equals("-f")) {
file f = new file(args[3]);
int len = (int)f.length(); // figure out how big the file is
message = new byte[len]; // create a buffer big enough
fileinputstream in = new fileinputstream(f);
int bytes_read = 0, n;
do { // loop until we've read it all
n = in.read(message, bytes_read, len-bytes_read);
bytes_read += n;
} while((bytes_read < len)&& (n != -1));
}
else { // otherwise, just combine all the remaining arguments.
string msg = args[2];
for (int i = 3; i < args.length; i++) msg += " " + args[i];
message = msg.getbytes();
}

// get the internet address of the specified host
inetaddress address = inetaddress.getbyname(host);

// initialize a datagram packet with data and address
datagrampacket packet = new datagrampacket(message, message.length,
address, port);

// create a datagram socket, send the packet through it, close it.
datagramsocket dsocket = new datagramsocket();
dsocket.send(packet);
dsocket.close();
}
catch (exception e) {
system.err.println(e);
system.err.println(usage);
}
}
}


//udpreceive.java
import java.io.*;
import java.net.*;

/**
* this program waits to receive datagrams sent the specified port.
* when it receives one, it displays the sending host and prints the
* contents of the datagram as a string. then it loops and waits again.
**/
public class udpreceive {
public static final string usage = "usage: java udpreceive ";
public static void main(string args[]) {
try {
if (args.length != 1)
throw new illegalargumentexception("wrong number of args");

// get the port from the command line
int port = integer.parseint(args[0]);

// create a socket to listen on the port.
datagramsocket dsocket = new datagramsocket(port);

// create a buffer to read datagrams into. if anyone sends us a
// packet containing more than will fit into this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];

// create a packet to receive data into the buffer
datagrampacket packet = new datagrampacket(buffer, buffer.length);

// now loop forever, waiting to receive packets and printing them.
for(;;) {
// wait to receive a datagram
dsocket.receive(packet);

// convert the contents to a string, and display them
string msg = new string(buffer, 0, packet.getlength());
system.out.println(packet.getaddress().gethostname() +
": " + msg);

// reset the length of the packet before reusing it.
// prior to java 1.1, we'd just create a new packet each time.
packet.setlength(buffer.length);
}
}
catch (exception e) {
system.err.println(e);
system.err.println(usage);
}
}
}

  在udp中主要的类是datagramsocket()和datagrampacket(),而在udpreceive中,被接受的字节是受限制,这些感觉不是太好,既然buf是一个字节数组,我们实在是很奇怪为什么构建器自己不能调查出数组的长度呢?唯一能猜测的原因就是c风格的编程使然,那里的数组不能自己告诉我们它有多大。

  而我们实际使用的过程中,当然不仅仅限于这些,其中要考虑有多台客户机来连接服务器,所以要考虑到线程thread的使用,如果再加上swing,就可以做一个类似于qq的socket功能了,这仅仅限于我在学习socket时的一些领悟。供大家参考。

扫描关注微信公众号