📄 18.txt
字号:
例程18-1
//TimeOutDemo.java
import java.net.*;
class TimeOutDemo
{
public static void main(String[] args)
{
SocketImpl impl = new MyPlainSocketImpl();
Try
{
//设置超时时长为1秒
impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(1000));
int timeout =
((Integer)impl.getOption(SocketOptions.SO_TIMEOUT)).intValue();
}
catch (java.io.IOException e)
{
System.out.println(e);
}
}
}
例程18-2
//SetSendBufferDemo.java
import java.net.*;
class SetSendBufferDemo
{
public static void main(String[] args)
{
SocketImpl impl = new MyPlainSocketImpl();
Try
{
// 设置发送缓冲区为1K字节
impl.setOption(SocketOptions.SO_SNDBUF, new Integer(1024));
// 读取缓冲区所用的大小
int size =
((Integer)(impl.getOption(SocketOptions.SO_SNDBUF))).intValue();
}
catch (java.io.IOException e)
{
System.out.println(e);
}
}
}
例程18-3
//EchoChar.java
import java.io.*;
import java.net.*;
public class EchoChar
{
public static void main(String[] args) throws IOException
{
//申请套接字资源
Socket echoSocket = null;
//申请数据输入、输出流
DataOutputStream out = null;
DataInputStream in = null;
try
{
//创建套接字
echoSocket = new Socket(10.65.111.101, 7);
//获取数据输出流
out = new DataOutputStream(echoSocket.getOutputStream());
//获取数据输入流
in = new DataInputStream(echoSocket.getInputStream());
}
catch(UnknownHostException e)
{
System.err.println("Don't know about host");
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
//将系统的标准输入设备作为数据输入流
DataInputStream stdIn = new DataInputStream(System.in);
String userInput;
//读取用户输入
while ((userInput = stdIn.readLine()) != null)
{
//向Socket的输出流写出字符
out.writeBytes(userInput);
out.writeByte('\n');
//从Socket输入流中读取,并打印
System.out.println("echo: " + in.readLine());
}
//关闭输入输出流
out.close();
in.close();
stdIn.close();
//关闭套接字
echoSocket.close();
}
}
例程18-4
//CommClient.java
import java.io.*;
import java.net.*;
public class CommClient
{
public static void main(String[] args) throws IOException
{
//申请Socket
Socket comSocket = null;
//申请数据输入输出流
PrintStream out = null;
DataInputStream in = null;
try
{
//创建Socket
comSocket = new Socket(10.65.111.101,1800);
//创建输出流
out = new PrintStream(comSocket.getOutputStream());
//创建输入流
in = new DataInputStream(comSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host");
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
//获取键盘输入流
DataInputStream stdIn = new DataInputStream(System.in);
String fromServer;
String fromUser;
//从键盘读入字符
while ((fromServer = in.readLine()) != null)
{
System.out.println("Server: " + fromServer);
//如果输入bye,程序退出
if (fromServer.equals("Bye."))
break;
//读字符
fromUser = stdIn.readLine();
//将客户输入发送给服务器
if (fromUser != null)
{
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
//关闭输入输出流
out.close();
in.close();
stdIn.close();
//关闭套接字
comSocket.close();
}
}
例程18-5
//CommServer.java
import java.net.*;
import java.io.*;
public class CommServer
{
public static void main(String[] args) throws IOException
{
//申请服务器ServerSocket
ServerSocket serverSocket = null;
try
{
//创建ServerSocket
serverSocket = new ServerSocket(1800);
}
catch (IOException e)
{
System.err.println("Could not listen on port.");
System.exit(1);
}
//申请用于连接的Socket
Socket clientSocket = null;
try
{
//获取用于连接的Socket
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
//获取输出流
PrintStream out = new PrintStream(
new BufferedOutputStream(
clientSocket.getOutputStream(), 1024), false);
//获取输入流
DataInputStream in = new DataInputStream(
new BufferedInputStream(
clientSocket.getInputStream()));
String inputLine, outputLine;
//设置信息交换协议
GreetingsProtocol greetings = new GreetingsProtocol();
//取得当前协议
outputLine = greetings.processInput(null);
out.println(outputLine);
out.flush();
//接收客户机的服务
while ((inputLine = in.readLine()) != null)
{
//处理客户机信息
outputLine = greetings.processInput(inputLine);
out.println(outputLine);
out.flush();
if (outputLine.equals("Bye."))
break;
}
//关闭输入输出流
out.close();
in.close();
//关闭套接字
clientSocket.close();
serverSocket.close();
}
}
例程18-6
// GreetingsProtocol.java
import java.net.*;
import java.io.*;
public class GreetingsProtocol
{
private static final int WAITING = 0;
private static final int SENTKNOCKKNOCK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;
private static final int NUMJOKES = 5;
private int state = WAITING;
private int currentJoke = 0;
private String[] clues =
{ "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
private String[] answers =
{ "Turnip the heat, it's cold in here!",
"I didn't know you could yodel!",
"Bless you!",
"Is there an owl in here?",
"Is there an echo in here?" };
public String processInput(String theInput)
{
String theOutput = null;
if (state == WAITING)
{
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
}
else if (state == SENTKNOCKKNOCK)
{
if (theInput.equalsIgnoreCase("Who's there?"))
{
theOutput = clues[currentJoke];
state = SENTCLUE;
}
else
{
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
}
else if (state == SENTCLUE)
{
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?"))
{
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
}
else
{
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER)
{
if (theInput.equalsIgnoreCase("y"))
{
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
}
else
{
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
例程18-7
//MultiServer.java
import java.net.*;
import java.io.*;
public class MultiServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
boolean listening = true;
try
{
serverSocket = new ServerSocket(1800);
}
catch (IOException e)
{
System.err.println("Could not listen on port");
System.exit(-1);
}
while (listening)
new MultiServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
例程18-8
//MultiServerThread.java
import java.net.*;
import java.io.*;
public class KKMultiServerThread extends Thread
{
private Socket socket = null;
public KKMultiServerThread(Socket socket)
{
super("KKMultiServerThread");
this.socket = socket;
}
public void run()
{
try
{
DataInputStream in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
PrintStream out = new PrintStream(
new BufferedOutputStream(socket.getOutputStream(), 1024), false);
String inputLine, outputLine;
GreetingsProtocol greetings = new GreetingsProtocol();
outputLine = greetings.processInput(null);
out.println(outputLine);
out.flush();
while ((inputLine = in.readLine()) != null)
{
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
out.flush();
if (outputLine.equals("Bye"))
break;
}
out.close();
in.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
例程18-9
// QuoteServerThread.java
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServerThread extends Thread
{
private DatagramSocket socket = null;
private DataInputStream in = null;
private boolean moreQuotes = true;
public QuoteServerThread() throws IOException
{
super("QuoteServerThread");
socket = new DatagramSocket(1800);
try
{
in = new DataInputStream(new FileInputStream("one-liners.txt"));
}
catch (FileNotFoundException e)
{
System.err.println("Could not open quote file. Serving time instead.");
}
}
public void run()
{
while (moreQuotes)
{
try
{
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// figure out response
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextQuote();
dString.getBytes(0, dString.length(), buf, 0);
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}
catch (IOException e)
{
e.printStackTrace();
moreQuotes = false;
}
}
socket.close();
}
private String getNextQuote()
{
String returnValue = null;
try
{
if ((returnValue = in.readLine()) == null)
{
in.close();
moreQuotes = false;
returnValue = "No more quotes. Goodbye.";
}
}
catch (IOException e)
{
returnValue = "IOException occurred in server.";
}
return returnValue;
}
}
例程18-10
// QuoteClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteClient
{
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.out.println("Usage: java QuoteClient <hostname>");
return;
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet =
new DatagramPacket(buf, buf.length, address, 1800);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData(), 0);
System.out.println("Quote of the Moment: " + received);
socket.close();
}
}
例程18-11
//QuoteServer.java
public class QuoteServer
{
public static void main(String[] args) throws java.io.IOException
{
new QuoteServerThread().start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -