我正在制作一个java应用程序,我需要的是有多个客户端,每个客户端都必须连接到不同的端口或同一端口(User Choice)。所以我使用多线程并在不同的端口上设置套接字来监听不同的客户端。我的问题是 1.客户端连接时出现SocketException 2.客户端和服务器之间的数据不发送/接收
服务器代码
package crawl_manager;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.sql.SQLException;
/**
*
* @author Harjinder
*/
public class crawler_server extends Thread {
url_dispacher udis;
db_Connection db;
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
public crawler_server(int port){
this.serverPort = port;
}
public crawler_server() throws IOException, SQLException
{
db =new db_Connection();
}
@SuppressWarnings("CallToThreadStopSuspendOrResumeManager")
public void startCrawler(int port) throws SQLException, IOException
{
crawler_server server = new crawler_server(port);
new Thread(server).start();
try {
Thread.sleep(2000 * 1000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Stopping Server");
server.stopabc();
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
@Override
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
new Thread(
new WorkerRunnable(
clientSocket, "Multithreaded Server")
).start();
}
System.out.println("Server Stopped.") ;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stopabc(){
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
}
WorkerRunnable代码
package crawl_manager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
public class WorkerRunnable implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
@Override
public void run() {
try {
long time;
try (
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream()
) {
time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +this.serverText + " - " + time + "").getBytes());
System.out.println(input.read()+"input he server ka");
}
System.out.println("Request processed: " + time);
} catch (IOException e) {
System.out.println(e);
}
}
}
客户代码
package crawler_client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Crawler_client {
/**
* @param args the command line arguments
*/
db_Connection db;
public Crawler_client()
{
this.db = new db_Connection();
}
/**
*
* @param sentence
* @throws SQLException
* @throws java.io.IOException
*/
@SuppressWarnings("empty-statement")
public void send(String sentence) throws SQLException, IOException
{
String ip = null;
int port = 0;
System.out.println(sentence);
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
String sql = "Select * from conn_settings where server='crawl_manager' ";
ResultSet rs = db.runSql(sql);
if(rs.next()){
port=Integer.parseInt(rs.getString("port"));
ip=(rs.getString("ip"));
}
else{
}
try
{
clientSocket = new Socket(ip, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: " + ip);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to: " + ip);
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null)
{
System.err.println( "Something is wrong. One variable is null." );
return;
}
try
{
while ( true )
{
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
int n = Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 ) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Trying to connect to unknown host: " + e);
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}