您好我是新來的Java套接字,我一直在嘗試創建一個服務器套接字。有人可以告訴我哪裏出錯了,因爲我收到錯誤說「地址已在使用中」。有時我沒有得到一個錯誤,但是它並沒有形成連接。請幫助?這是服務器類和客戶端類。套接字服務器無連接
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class MessageServer {
public static void main(String[] args) throws IOException{
int port = 8080;
//int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
while(true){
System.out.println("Waiting for client...");
Socket client = server.accept();
System.out.println("Client from " + client.getInetAddress() + " connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine = in.readLine();
System.out.println("Client said: '"+inputLine+"'");
Writer count = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
byte c [] = count.toString().getBytes();
count.flush();
}
}
}
import java.net.*;
import java.io.*;
public class MessageSendClient {
public static void man(String args[]) throws IOException{
Socket server1 = new Socket("143.210.72.82", 8080);
System.out.println("Connected to " + server1.getInetAddress());
InputStream in = server1.getInputStream();
byte c[] = new byte[100];
int num = in.read(c);
String count = new String(c);
System.out.println("Server said: " + count);
}
}
嘗試使用「localhost」而不是'143.210.72.82',並且不要使用已用於其他用途的8080端口號。 – Braj
可能你的程序在你每次運行它時都沒有關閉套接字,並且套接字只有在套接字超時後纔可用。 –
您已經同時運行兩次服務器。 – Braj