我很抱歉問這樣一個基本的問題,但我新的線程,socket編程。我正在嘗試編寫一個多線程套接字程序,但它總是給出錯誤。當我調試它時,我無法找到它爲什麼會給出這個愚蠢的錯誤。你能幫我解決我的錯誤嗎?如何在java中創建threadedsocket連接?
我的客戶端類:
public class Client {
public void run() throws IOException{
Socket s = new Socket("localhost",9999);
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(readFromConsole());
}
public String readFromConsole(){
String result ;
Scanner in = new Scanner(System.in);
result = in.nextLine();
return result;
}
public static void main(String[] args) throws Exception {
Client c = new Client();
c.run();
}
}
我的服務器類:
public class Server {
ServerSocket ss;
public void run() throws IOException{
ss = new ServerSocket(9999);
while(true){
TestForThread t;
try {
t = new TestForThread(ss.accept());
Thread testThread = new Thread(t);
testThread.start();
} catch(IOException e){
e.printStackTrace();
}
}
//BufferedReader br =
//new BufferedReader(new InputStreamReader(sForAccept.getInputStream()));
//String temp = br.readLine();
//System.out.println(runCommand(temp));
}
protected void finalize() {
// Objects created in run method are finalized when
// program terminates and thread exits
try {
ss.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) throws Exception{
Server s = new Server();
s.run();
}
}
我的線程類::
public class TestForThread implements Runnable {
private Socket client;
public TestForThread(Socket c){
client = c;
}
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
line = in.readLine();
String commandResult = runCommand(line);
System.out.println(commandResult);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
public String runCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
String answer = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
answer = answer + line + "\n";
}
return answer;
}
}
非常感謝你。
我看不出哪裏是在你的程序中的線程。你只需從cmd讀取一行並將其發送到套接字 –
@Dan Bizdadea:我在Server類中使用它。在我的跑步方法。 – mehmetozer
你得到的錯誤是什麼? – Jesper