您的位置:首页 > 编程语言 > Java开发

【Java】SingleTalkServer代码理解与学习笔记

2017-03-15 18:54 645 查看
java课程设计算是正式开始了,要求是做一个简单的聊天软件出来,老师把相关的核心代码发给了我们,要求我们能够在核心代码的基础上对聊天器的功能进行修改和完善。代码共有3段,分别是:SingleTalkServer,SingleTalkClient,MultiTalkServer。

分别对应:单人聊天服务器,单人聊天客户端,多人聊天服务器。

今天我们先来学习SingleTalkServer的相关内容。

下面是完整代码:
import java.net.*;
import java.io.*;

public class SingleTalkServer {
public static void main(String[] args) throws IOException
{

ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}

Socket clientSocket = null;
try {
clientSocket = serverSocket.accept(); //程序将在此等候客户端的连接
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println("Accept OK!");

//打开输入/输出流
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); //auto flush
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));

//从标准输入流(键盘)中获取信息
BufferedReader sin = new BufferedReader( new InputStreamReader( System.in ) );

boolean sinbye = false;
boolean inbye = false;
String sinputLine, inputLine;

inputLine = in.readLine();
System.out.println( "from Client: " + inputLine );

System.out.print("Server input:");
sinputLine = sin.readLine();

while( true )
{
if( sinbye == false )
{
out.println(sinputLine);
out.flush();
//System.out.println("Server: " + sinputLine);

if (sinputLine.equals("Bye."))
sinbye = true;
}

if( inbye == false )
{
inputLine = in.readLine();
System.out.println( "from Client: " + inputLine );

if (inputLine.equals("Bye."))
inbye = true;
}

if( sinbye == false )
{
System.out.print("Server input:");
sinputLine = sin.readLine();
}

if( sinbye == true && inbye == true )
break;
}

out.close();
in.close();
sin.close();

clientSocket.close();
serverSocket.close();
}
}
紧接在main后面的是抛出I/O异常,java标准库中对于IOException的描述为:

public class
IOException extends
Exception
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

这是Exception的子类,用于出现失败或者中断输入/输出的时候,抛出异常。

接下来是ServerSocket,我们先来研究这个单词,中文含义是服务器套接字。

百度百科中对于它的定义是:

      源IP地址和目的IP地址以及源端口号和目的端口号的组合称为套接字。其用于标识客户端请求的服务器和服务。

      它是网络通信过程中端点的抽象表示,包含进行网络通信必需的五种信息:连接使用的协议,本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程的协议端口。

java标准库中对于ServerSocket的描述为:

public class
ServerSocket extends
Object implements
Closeable
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

The actual work of the server socket is performed by an instance of the 
SocketImpl
 class.
An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall.
其常用的构造器表示有:

ServerSocket()


Creates an unbound server socket.
ServerSocket(int port)


Creates a server socket, bound to the specified port.
ServerSocket(int port,
int backlog)


Creates a server socket and binds it to the specified local port number, with the specified backlog.
ServerSocket(int port,
int backlog, InetAddress bindAddr)


Create a server with the specified port, listen backlog, and local IP address to bind to.
代码中对于serversocket的初始化是用上表中的第二个构造器来实现的,初始化参数是4444端口。

在这里,代码中抛出了一个异常:如果用4444端口初始化失败,则程序终止。

继续向下阅读代码,可以看到又出现了Socket类,查阅java标准库可知:

public class Socket extends Object

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the 
SocketImpl
 class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

简单来讲这样一个类可以建立起两台机器之间的通讯。
此时调用了ServerSocket的一个方法accept,程序将在此等候客户端的链接。如果连接失败,将终止程序。

接下来的一段代码又用到了两个新的类:PrintWriter和BufferdReader。

前者是打开输出流,后者是打开输入流。

以下是java标注库中对于这两个类的介绍:

public class PrintWriter
extends Writer

Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in
PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf,
or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking
checkError().

public class
BufferedReader
extends
Reader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

BufferedReader in

= new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations
may be costly, such as FileReaders and InputStreamReaders. For example,

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

后面的全部代码就是从标准输入流(键盘)中获取信息传输到服务器中,以及如何结束程序的有关内容。

值得注意的是,如果服务器端和客户端全都输入的是“Bye.”,整个程序才能正常结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 服务器