利用 socket 模擬qq 的消息發送和接收功能。既可以接收消息,也可以發送消息,無論是server 還是 client。在server 和 client 端都開啟了兩個線程, 一個線程用於接收並打印消息,一個線程用於發送消息。
先啟動 server ,後啟動client 去連接server, client 端拋出異常,說, socket 獲取outputStream失敗。。找不到原因啊。。oh。 求高手解答。
package com.corejava.chapter3;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class AnalogQQClient
{
public static void main(String[] args) throws IOException
{
try(Socket socket = new Socket("127.0.0.1", 8189))
{
new Thread(new Runnable() // print server's info
{
@Override
public void run()
{
try
{
Scanner scanner = new Scanner(socket.getInputStream());
while(true)
{
if(scanner.hasNext())
{
String line = scanner.nextLine();
System.out.println("from client: " + line);
if(line.equals("bye"))
{
break;
}
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() // send info typed to the server
{
@Override
public void run()
{
try
{
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while(true)
{
Scanner scanner = new Scanner(System.in);
if(scanner.hasNext())
{
writer.println("from server: " + scanner.nextLine());
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
finally
{
System.out.println("the client is closed !");
}
}
}
package com.corejava.chapter3;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class AnalogQQServer
{
public static void main(String[] args) throws IOException
{
try(ServerSocket serverSocket = new ServerSocket(8189))
{
Socket socket = serverSocket.accept();
new Thread(new Runnable() // print client's info
{
@Override
public void run()
{
try
{
Scanner scanner = new Scanner(socket.getInputStream());
while(true)
{
if(scanner.hasNext())
{
String line = scanner.nextLine();
System.out.println("from client: " + line);
if(line.equals("bye"))
{
break;
}
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() // send info typed to the client
{
@Override
public void run()
{
try
{
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
while(true)
{
Scanner scanner = new Scanner(System.in);
if(scanner.hasNext())
{
writer.println("from server: " + scanner.nextLine());
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
finally
{
System.out.println("the server is closed !");
}
}
}
分析了下你的代碼,根本原因是你用了jdk1.7的try()操作,將客戶端的Socket寫在try()後面了,導致啟動的兩個線程還在使用socket時,jdk已經自動將該socket關閉了。
修改方法很簡單,將Client端的try()括號裡面的代碼挪到{}中,然後使用完成後手動關閉。
try {
Socket socket = new Socket("127.0.0.1", 8189);
這樣修改後就可以正常通信了,但是你的通信終止操作還需要再設計下,因為你是開啟了多個線程來通信的,怎麼讓客戶端在收到bye的消息後也終止發送呢?
這個我覺得你還需要認真思考下。祝好,有問題再交流。