我有一个使用JLabel
的服务器 - 客户端程序,我正在尝试与特定客户端进行通信。当我接受任何客户端时,我将socket
添加到ArrayList<Socket>
,然后我将socket = socketList.get(1);
分配给我的第一个JLabel
,以便套接字将包含连接到服务器的第一个客户端。但是没有发生任何沟通。我无法确定问题。
//服务器
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
PrintWriter out;
try {
socket = socketList.get(2);
out = new PrintWriter(socket.getOutputStream(), true);
out.println("pc2");
} catch (IOException ex) {
Logger.getLogger(third_frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void postListen()
{
new Thread(new Runnable()
{
public void run()
{
connect_clients();
}
}).start();
}
//checking clients connected
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
try {
while (true) {
//socket = listener.accept();
socketList.add(listener.accept());
try {
clientIP = socket.getLocalAddress().getHostName();
}
finally
{
}
}
}
finally
{
}
}
catch(IOException ex)
{
}
}
//客户端
void connect_server()
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
}
}
catch (IOException ex) {
Logger.getLogger(client_form.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:3)
对我而言似乎你没有初始化你的套接字然后尝试调用它,但是如果没有所有代码和错误,很难知道什么是错的。
//socket = listener.accept();
socketList.add(listener.accept());
try {
clientIP = socket.getLocalAddress().getHostName();