我正在嘗試使用服務器和客戶端來回傳遞文本字符串的簡單程序。我無法建立連接。我有一個測試打印線在套接字接受線的下面,它從不打印,所以我認爲問題在那裏,但我不知道如何做更徹底的檢查。未能接受Java中的套接字連接
我已經在Eclipse中編寫了這個程序,如果這有所作爲。
這是服務器:
import java.io.*;
import java.net.*;
public class HW2Q1S {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
//data xfer
BufferedReader sIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter sOut = new PrintWriter(skt.getOutputStream(), true);
//string receiving
int count = 1;
String msg = "";
while((msg = sIn.readLine()) != null) {
while(count < 11) {
msg = sIn.readLine();
System.out.println("Received: "+ msg);
String returnMsg = msg.toUpperCase();
System.out.println("Capped: "+ returnMsg);
sOut.write(returnMsg);
count++;
}
} //end of read from client in while loop
if (count == 10) {
System.out.println("Max reached.");
}
srvr.close();
return;
}
catch(Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
這是客戶端:
import java.util.Random;
import java.io.*;
import java.net.*;
public class HW2Q1C {
public static void main(String[] args) throws IOException {
String capped = "";
String temp = "";
try {
//make the connection
Socket skt = new Socket("localhost", 7654);
BufferedReader cIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter cOut = new PrintWriter(skt.getOutputStream(), true);
//send 11 strings
for (int i = 0; i < 11; i++) {
temp = Stringer();
cOut.write(temp);
System.out.println("Sending: " + temp);
}
//receive server strings
while(cIn.readLine() != null) {
capped = cIn.readLine();
System.out.println("From server: "+ capped);
}
skt.close();
} // end of connection try block
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
謝謝!
我想發生一個異常,stacktrace是什麼?你嘗試過調試嗎? – Altoyyr
這就是我的想法,但控制檯中沒有任何東西。它完全是空的。 – TurtleOrRodeo
我剛剛運行你的程序,並且據我所知,連接本身就好。 srvr.accept()等到客戶端連接(它正確地執行)也許這是額外的幫助http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html – Altoyyr