我试图使用java套接字创建一个简单的客户端 - 服务器程序。客户端和服务器从控制台发送他们从键盘接收的其他号码。但是,在客户端从服务器收到号码并尝试下一个号码后,服务器没有从客户端接收号码并且程序冻结。我是Java的初学者,我不知道自己做错了什么。
服务器代码:
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TicServer
{
private boolean myTurn ;
private ServerSocket sock;
private Socket s;
private Scanner input;
private PrintStream output;
private Scanner sc;
public TicServer() throws UnknownHostException, IOException
{
myTurn = false;
sock = new ServerSocket(9001);
s = null;
sc = new Scanner(System.in);
}
public void run() throws IOException
{
while(true)
{
if(this.myTurn == true)
{
int pos;
this.myTurn = false;
System.out.println("(Server) Insert number: ");
pos = sc.nextInt();
output.println(pos);
}
else
{
int pos;
this.myTurn = true;
s = sock.accept();
input = new Scanner(s.getInputStream());
output = new PrintStream(s.getOutputStream());
pos = input.nextInt();
System.out.println("Server received: " + pos);
}
}
}
private void close() throws IOException
{
this.sock.close();
this.sc.close();
this.input.close();
this.output.close();
}
public static void main(String args[])
{
TicServer ts = null;
try
{
ts = new TicServer();
ts.run();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
ts.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
和客户端代码:
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TicClient
{
private boolean myTurn ;
private Socket sock;
private Scanner input;
private PrintStream output;
private Scanner sc;
public TicClient() throws UnknownHostException, IOException
{
myTurn = true;
sock = new Socket("127.0.0.1", 9001);
sc = new Scanner(System.in);
input = new Scanner(sock.getInputStream());
output = new PrintStream(sock.getOutputStream());
}
public void run()
{
while(true)
{
if(this.myTurn == true)
{
int pos;
this.myTurn = false;
System.out.println("(client)Insert number: ");
sc = new Scanner(System.in);
pos = sc.nextInt();
output.println(pos);
}
else
{
int pos;
this.myTurn = true;
pos = input.nextInt();
System.out.println("Client received: " + pos);
}
}
}
private void close() throws IOException
{
this.sock.close();
this.sc.close();
this.input.close();
this.output.close();
}
public static void main(String args[])
{
TicClient tc = null;
try
{
tc = new TicClient();
tc.run();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
tc.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
我使用Eclipse在同一台计算机上运行这两个程序。