편집 : Ik 길지만 누구든지 소켓을 프로그래밍하는 방법을 알고 있습니까?Java 소켓 : 서버 입력 스트림이 클라이언트 출력 스트림에서 읽히지 않습니까?
내 문제는 나를 조금 혼란스럽게합니다. 한 대의 컴퓨터에서 서버를 실행하고 다른 컴퓨터에서 클라이언트를 연결했습니다. 클라이언트에서 콘솔로 메시지를 입력하여 보내면 서버가 메시지를받지 못하는 것입니다. 왜 내가 지난 3 시간 동안 콘솔에 인쇄를 테스트했기 때문에 아무도 알지 못합니다. 알아낼 수 없기 때문입니다. 나는 소켓에 비교적 새롭기 때문에 내가 단지 바보가된다면 너무 가혹하지는 마라.
Heres는 클라이언트 측에 대한 내 코드 :
import java.io.IOException;
import java.net.*;
public class MultipleSocketServer {
public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = {"", ""};
public static ServerSocket socket;
public static void main(String[] args) {
System.out.println("Server starting...");
try {
ServerSocket socket = new ServerSocket(port);
while(true) {
Socket connection = socket.accept();
String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
loop:
for(int i = 0; i < connected.length; i++) {
if(connected[0].equals(ip) || connected[1].equals(ip)) {
break loop;
}else if(!connected[i].equals(ip)) {
connected[i] = ip;
System.out.println(ip);
MultiServer_Client client = new MultiServer_Client(connection, i);
Thread run = new Thread(client);
run.start();
break loop;
}
}
}
} catch (IOException e1) {
System.out.println("Could not bind server on: " + port);
System.exit(-1);
}
}
}
그리고 여기에 연결된 각 클라이언트를 처리하는 내 코드입니다 : 여기
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class SocketClient {
public static void main(String [] args) {
String host = "************";
int port = 25565;
StringBuffer instr = new StringBuffer();
String TimeStamp;
System.out.println("SocketClient initialized");
try {
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
TimeStamp = new java.util.Date().toString();
String process = "Server called on " + host + ":" + port + " at " + TimeStamp + ": " + message + (char) 13;
osw.write(process);
osw.flush();
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
int c;
while ((c = isr.read()) != 13)
instr.append((char) c);
connection.close();
System.out.println(instr);
} catch (UnknownHostException e) {
System.err.println("UnknownHostException: " + e);
} catch (IOException e) {
System.err.println("IOExcepion: " + e);
}
}
}
서버에 클라이언트를 연결하는 코드는 다음과 같습니다
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class MultiServer_Client implements Runnable {
public String time;
public Socket client;
public StringBuffer process = new StringBuffer();
public BufferedInputStream inputStream;
public InputStreamReader reader;
public BufferedOutputStream outputStream;
public OutputStreamWriter writer;
public boolean connected = true;
public int ID;
public MultiServer_Client(Socket connection, int i) {
client = connection;
ID = i;
try {
inputStream = new BufferedInputStream(client.getInputStream());
reader = new InputStreamReader(inputStream);
outputStream = new BufferedOutputStream(client.getOutputStream());
writer = new OutputStreamWriter(outputStream, "US-ASCII");
} catch (IOException e) {
System.out.println("IOException: " + e);
}
System.out.println("Client connected...");
write("Connected to " + MultipleSocketServer.name);
}
public void run() {
while(connected) {
write("hi");
}
System.out.println("Disconnecting client...");
}
public void write(String authen) {
try {
time = new java.util.Date().toString();
String message = time + ": " + authen + (char) 13;
writer.write(message);
writer.flush();
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
public void read() {
//read from client
int character;
process = new StringBuffer();
try {
while ((character = reader.read()) != 13) {
process.append((char) character);
}
System.out.println(process);
process.delete(0, process.length());
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
}
나는별로 도움이되지 않는다. 내가 말했듯이, 나는 소켓에 새로운 사람이 아무 문제가있을 것 같습니다 ... 감사 :
당신은 예외 예외 자체를 로그인하지 않고 발생할 때마다 자동으로 해제 될 것으로 보인다. 서버가 클라이언트 연결을 끊기 때문에 예외가 코드에서 발생할 수 있습니까? – Dawood
서버의 write() 및 read() 메소드에서 코드가 예외를 발생 시키면 클라이언트를 닫을 때와 마찬가지로 서버가 종료됩니다. 어떤 예외가있을 때 클라이언트 클래스의 모든 것을 인쇄하고 있습니다. 나는 정말로 hahaha 여기에서 비빈다. 그래도 조언 주셔서 감사합니다. – MrDrProfessorTyler
또한 socket.accept()를 반복하여 클라이언트를 서버에 연결하면 read() 및 write()가 제대로 작동하고 연결이 완벽하게 작동하지만 다른 클라이언트와 컴퓨터를 추적 할 수 없습니다 무한대의 클라이언트가 서버에서 실행될 수 있습니다. 고칠 방법이 없나요? – MrDrProfessorTyler