您好我想了解如何套接字工作可以實現一個多玩家端到壟斷game.I理解如何創建連接,但現在看來我有困難之間發送和接收數據客戶端和服務器。這裏是我的代碼:Java套接字發送和接收數據
客戶端代碼:
public class EchoClient
{
public static void main(String[] args)
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
echoSocket = new Socket("127.0.0.1", 5000);;
out = new PrintWriter(echoSocket.getOutputStream());
in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: taranis");
}
catch (IOException e)
{
System.err.println("Couldent get I/O for "
+ " the connection to : taranis.");
}
}
}
Server代碼:
public class ServerSide
{
ServerSocket connect;
Socket connection;
PrintWriter out;
BufferedReader in;
public void go()
{
try
{
connect = new ServerSocket(5000);
connection = connect.accept();
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
System.out.println("echo: " + in.readLine());
}
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
new ServerSide().go();
}
}
,我想在這裏創建一個簡單的connectio n在客戶端和服務器之間。在客戶端,當用戶輸入數據時,我希望它被髮送到服務器,然後將它打印在服務器控制檯上。看起來,我喜歡代碼它不工作的方式是什麼我做錯了?
定義 「不工作」。 – EJP