导读:
网络编程中最重要的就是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 <hostname><port><msg>...\n" + <br> " or: java UDPSend <hostname><port> -f <file>"; <br> public static void main(String args[]) { <br> try { <br> // Check the number of arguments <br> if (args.length throw new IllegalArgumentException("Wrong number of args"); <br> <br> // Parse the arguments <br> String host = args[0]; <br> int port = Integer.parseInt(args[1]); <br> <br> // Figure out the message to send. <br> // If the third argument is -f, then send the contents of the file <br> // specified as the fourth argument. Otherwise, concatenate the <br> // third and all remaining arguments and send that. <br> byte[] message; <br> if (args[2].equals("-f")) { <br> File f = new File(args[3]); <br> int len = (int)f.length(); // figure out how big the file is <br> message = new byte[len]; // create a buffer big enough <br> FileInputStream in = new FileInputStream(f); <br> int bytes_read = 0, n; <br> do { // loop until we've read it all <br> n = in.read(message, bytes_read, len-bytes_read); <br> bytes_read += n; <br> } while((bytes_read <len> } <br> else { // Otherwise, just combine all the remaining arguments. <br> String msg = args[2]; <br> for (int i = 3; i <args.length args msg i> message = msg.getBytes(); <br> } <br> <br> // Get the internet address of the specified host <br> InetAddress address = InetAddress.getByName(host); <br> <br> // Initialize a datagram packet with data and address <br> DatagramPacket packet = new DatagramPacket(message, message.length, <br> address, port); <br> <br> // Create a datagram socket, send the packet through it, close it. <br> DatagramSocket dsocket = new DatagramSocket(); <br> dsocket.send(packet); <br> dsocket.close(); <br> } <br> catch (Exception e) { <br> System.err.println(e); <br> System.err.println(usage); <br> } <br> } <br> } <br> //UDPreceive.java <br> import java.io.*; <br> import java.net.*; <br> /** <br> * This program waits to receive datagrams sent the specified port. <br> * When it receives one, it displays the sending host and prints the <br> * contents of the datagram as a string. Then it loops and waits again. <br> **/ <br> public class UDPReceive { <br> public static final String usage = "Usage: java UDPReceive <port> public static void main(String args[]) { <br> try { <br> if (args.length != 1) <br> throw new IllegalArgumentException("Wrong number of args"); <br> <br> // Get the port from the command line <br> int port = Integer.parseInt(args[0]); <br> <br> // Create a socket to listen on the port. <br> DatagramSocket dsocket = new DatagramSocket(port); <br> <br> // Create a buffer to read datagrams into. If anyone sends us a <br> // packet containing more than will fit into this buffer, the <br> // excess will simply be discarded! <br> byte[] buffer = new byte[2048]; <br> <br> // Create a packet to receive data into the buffer <br> DatagramPacket packet = new DatagramPacket(buffer, buffer.length); <br> // Now loop forever, waiting to receive packets and printing them. <br> for(;;) { <br> // Wait to receive a datagram <br> dsocket.receive(packet); <br> // Convert the contents to a string, and display them <br> String msg = new String(buffer, 0, packet.getLength()); <br> System.out.println(packet.getAddress().getHostName() + <br> ": " + msg); <br> // Reset the length of the packet before reusing it. <br> // Prior to Java 1.1, we'd just create a new packet each time. <br> packet.setLength(buffer.length); <br> } <br> } <br> catch (Exception e) { <br> System.err.println(e); <br> System.err.println(usage); <br> } <br> } <br> } <br> 在UDP中主要的类是DatagramSocket()和DatagramPacket(),而在UDPreceive中,被接受的字节是受限制,这些感觉不是太好,既然buf是一个字节数组,我们实在是很奇怪为什么构建器自己不能调查出数组的长度呢?唯一能猜测的原因就是C风格的编程使然,那里的数组不能自己告诉我们它有多大。 <br> 而我们实际使用的过程中,当然不仅仅限于这些,其中要考虑有多台客户机来连接服务器,所以要考虑到线程Thread的使用,如果再加上SWING,就可以做一个类似于QQ的SOCKET功能了,这仅仅限于我在学习SOCKET时的一些领悟。供大家参考。 <br> - <br> 主页: http://www.fls-cts.com/kkjvk/ <br> 网络编程中最重要的就是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 <hostname><port><msg>...\n" + " or: java UDPSend <hostname><port> -f <file>"; public static void main(String args[]) { try { // Check the number of arguments if (args.length " final UDPReceive ** again. waits loops it Then string. as * prints host sending displays one, receives When specified sent program This java.net.*; import java.io.*; UDPreceive.java }} dsocket.close(); dsocket.send(packet); DatagramSocket(); close it, through send socket, port); address, message.length, DatagramPacket(message, address with Initialize InetAddress internet message="msg.getBytes();" <args.length i="3;" for arguments. remaining all combine otherwise else><br>本文转自 <br><a href="http://www.cn-java.com/www1/?action-viewnews-itemid-1863">http://www.cn-java.com/www1/?action-viewnews-itemid-1863</a></args.length></file></port></hostname></msg></port></hostname></port></args.length></len></file></port></hostname></msg></port></hostname>
网络编程中最重要的就是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 <hostname><port><msg>...\n" + <br> " or: java UDPSend <hostname><port> -f <file>"; <br> public static void main(String args[]) { <br> try { <br> // Check the number of arguments <br> if (args.length throw new IllegalArgumentException("Wrong number of args"); <br> <br> // Parse the arguments <br> String host = args[0]; <br> int port = Integer.parseInt(args[1]); <br> <br> // Figure out the message to send. <br> // If the third argument is -f, then send the contents of the file <br> // specified as the fourth argument. Otherwise, concatenate the <br> // third and all remaining arguments and send that. <br> byte[] message; <br> if (args[2].equals("-f")) { <br> File f = new File(args[3]); <br> int len = (int)f.length(); // figure out how big the file is <br> message = new byte[len]; // create a buffer big enough <br> FileInputStream in = new FileInputStream(f); <br> int bytes_read = 0, n; <br> do { // loop until we've read it all <br> n = in.read(message, bytes_read, len-bytes_read); <br> bytes_read += n; <br> } while((bytes_read <len> } <br> else { // Otherwise, just combine all the remaining arguments. <br> String msg = args[2]; <br> for (int i = 3; i <args.length args msg i> message = msg.getBytes(); <br> } <br> <br> // Get the internet address of the specified host <br> InetAddress address = InetAddress.getByName(host); <br> <br> // Initialize a datagram packet with data and address <br> DatagramPacket packet = new DatagramPacket(message, message.length, <br> address, port); <br> <br> // Create a datagram socket, send the packet through it, close it. <br> DatagramSocket dsocket = new DatagramSocket(); <br> dsocket.send(packet); <br> dsocket.close(); <br> } <br> catch (Exception e) { <br> System.err.println(e); <br> System.err.println(usage); <br> } <br> } <br> } <br> //UDPreceive.java <br> import java.io.*; <br> import java.net.*; <br> /** <br> * This program waits to receive datagrams sent the specified port. <br> * When it receives one, it displays the sending host and prints the <br> * contents of the datagram as a string. Then it loops and waits again. <br> **/ <br> public class UDPReceive { <br> public static final String usage = "Usage: java UDPReceive <port> public static void main(String args[]) { <br> try { <br> if (args.length != 1) <br> throw new IllegalArgumentException("Wrong number of args"); <br> <br> // Get the port from the command line <br> int port = Integer.parseInt(args[0]); <br> <br> // Create a socket to listen on the port. <br> DatagramSocket dsocket = new DatagramSocket(port); <br> <br> // Create a buffer to read datagrams into. If anyone sends us a <br> // packet containing more than will fit into this buffer, the <br> // excess will simply be discarded! <br> byte[] buffer = new byte[2048]; <br> <br> // Create a packet to receive data into the buffer <br> DatagramPacket packet = new DatagramPacket(buffer, buffer.length); <br> // Now loop forever, waiting to receive packets and printing them. <br> for(;;) { <br> // Wait to receive a datagram <br> dsocket.receive(packet); <br> // Convert the contents to a string, and display them <br> String msg = new String(buffer, 0, packet.getLength()); <br> System.out.println(packet.getAddress().getHostName() + <br> ": " + msg); <br> // Reset the length of the packet before reusing it. <br> // Prior to Java 1.1, we'd just create a new packet each time. <br> packet.setLength(buffer.length); <br> } <br> } <br> catch (Exception e) { <br> System.err.println(e); <br> System.err.println(usage); <br> } <br> } <br> } <br> 在UDP中主要的类是DatagramSocket()和DatagramPacket(),而在UDPreceive中,被接受的字节是受限制,这些感觉不是太好,既然buf是一个字节数组,我们实在是很奇怪为什么构建器自己不能调查出数组的长度呢?唯一能猜测的原因就是C风格的编程使然,那里的数组不能自己告诉我们它有多大。 <br> 而我们实际使用的过程中,当然不仅仅限于这些,其中要考虑有多台客户机来连接服务器,所以要考虑到线程Thread的使用,如果再加上SWING,就可以做一个类似于QQ的SOCKET功能了,这仅仅限于我在学习SOCKET时的一些领悟。供大家参考。 <br> - <br> 主页: http://www.fls-cts.com/kkjvk/ <br> 网络编程中最重要的就是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 <hostname><port><msg>...\n" + " or: java UDPSend <hostname><port> -f <file>"; public static void main(String args[]) { try { // Check the number of arguments if (args.length " final UDPReceive ** again. waits loops it Then string. as * prints host sending displays one, receives When specified sent program This java.net.*; import java.io.*; UDPreceive.java }} dsocket.close(); dsocket.send(packet); DatagramSocket(); close it, through send socket, port); address, message.length, DatagramPacket(message, address with Initialize InetAddress internet message="msg.getBytes();" <args.length i="3;" for arguments. remaining all combine otherwise else><br>本文转自 <br><a href="http://www.cn-java.com/www1/?action-viewnews-itemid-1863">http://www.cn-java.com/www1/?action-viewnews-itemid-1863</a></args.length></file></port></hostname></msg></port></hostname></port></args.length></len></file></port></hostname></msg></port></hostname>
本文深入讲解Java中的SOCKET编程,包括TCP和UDP协议的应用,并提供具体示例代码,如客户端和服务端的实现。
2915

被折叠的 条评论
为什么被折叠?



