我是java新手,我正在尝试学习如何使用套接字。
我正在尝试编写一个简单的文本信使,服务器 - 客户端,但我不知道如何让服务器始终监听客户端的流:
这是服务器代码,现在它只管理 1 个传入连接,当客户端连接时,服务器向它发送一条消息:
import java.net.*;
import java.io.*;
public class SocketServer {
private InetAddress ServerAddress;
private int ServerPort;
private int ServerQueue;
private ServerSocket Server;
public SocketServer(String ServerAddress, int ServerPort, int ServerQueue)
{
try
{
this.ServerAddress = InetAddress.getByName(ServerAddress);
}
catch (UnknownHostException uhe)
{
uhe.printStackTrace();
}
this.ServerPort = ServerPort;
}
public boolean ServerCreate()
{
try
{
Server = new ServerSocket(this.ServerPort, 10, this.ServerAddress);
System.out.println("System Message: Server started!");
return true;
}
catch(IOException ioe)
{
ioe.printStackTrace();
System.out.println("System Message: Can't start server!");
return false;
}
}
public void ServerStartListening()
{
int exit = -1;
while(exit < 1)
{
try
{
Socket client = this.Server.accept();
OutputStream clientout = client.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientout));
bw.write("Welcome: "+client.toString());
bw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
对不起,我的英语不好。