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
新闻热点
疑难解答