我正在尝试创建一个多线程的客户端-服务器通信程序,该程序使用2个线程连接到多个客户端(一次只能连接2个)。该程序的特点是:
客户端可以从客户端终止通信程序,但服务器线程不会退出。
在服务器程序满足退出条件之前,服务器中的线程不会关闭ServerSocket
,即,如果请求,服务器将保持连续运行,并持续连接到各个客户端。
每次客户端终止程序时,仅关闭通信(相关)流。
现在问题是在其中创建Socket
对象的代码行。调用accept()
对象的ServerSocket
方法后,将引发NullPointerException
。对我要去哪里出错的任何见解都将非常有帮助。
我的服务器端代码:
class Clientconnect implements Runnable
{
ServerSocket ss;
Socket s;
String n;
int f;
Clientconnect() throws Exception
{
new ServerSocket(776);
new Socket();
}
public void run()
{
n = Thread.currentThread().getName();
while(true) // thread iteration
{
try
{
System.out.println("Thread "+Thread.currentThread().getName()+" is ready to accept a
connection.....");
s = ss.accept(); // ------**The NullPointerException occurs here**
System.out.println("Thread "+Thread.currentThread().getName()+" has accepted a connection:\n----------");
PrintStream ps = new PrintStream (s.getOutputStream());
BufferedReader cl = new BufferedReader (new InputStreamReader (s.getInputStream()));
BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));
String in, out;
ps.println("you are connected via thread "+n);
ps.println("----------------------");
while (true)
{
in = cl.readLine();
if( in.equalsIgnoreCase("system_exit"))
{
break;
}
System.out.println("Client : "+in);
System.out.print("Server "+n+" :");
out = kb.readLine();
ps.println(out);
}
s.close();
ps.close();
cl.close();
System.out.print("do you want to close the server socket\n1:close\n2:continue\nenter");
f = Integer.parseInt(kb.readLine());
if(f == 1)
{
ss.close();
break;
}
else
{
continue;
}
}
catch (Exception e){e.printStackTrace();}
}
}
}
class test2g
{
public static void main (String args[]) throws Exception
{
Clientconnect cc = new Clientconnect();
Thread t1 = new Thread (cc, "t1");
Thread t2 = new Thread (cc, "t2");
t1.start();
t2.start();
}
}
这是一个相当简单的通信程序,没有复杂的资源访问或检索。我在同一台计算机上运行客户端,因此它是“ localhost”。
我的客户端代码仅仅是try {}块的倒数。
P.S。我尝试在ServerSocket
类中将Socket
和Clientconnect
对象声明为静态对象,但没有帮助。
我相信ss
需要在构造函数中分配:
Clientconnect() throws Exception
{
ss = new ServerSocket(776);
new Socket(); // Not needed because it creates a Socket that is immediately thrown away.
}