[英]ArrayList of Socket doesn't work to send message to Client - Java
我有一個服務器客戶端程序,在其中使用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);
}
}
在我看來,您沒有初始化套接字然后嘗試調用它,但是如果沒有所有代碼和錯誤,很難知道出了什么問題。
//socket = listener.accept();
socketList.add(listener.accept());
try {
clientIP = socket.getLocalAddress().getHostName();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.