Сервер
import java.net.*;
import java.io.*;
public class server
{
private Socket socket;
private ServerSocket server;
// constructor with port
public void start(int port){
try {
server = new ServerSocket(port);
while(true){
socket = server.accept();
new Thread (new ConnectionHandler(socket)).start();
}
}catch(IOException i){
}
}
}
class ConnectionHandler extends Thread{
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
public ConnectionHandler(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try
{
System.out.println("Waiting for a client ...");
System.out.println("Client accepted");
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String[] args) {
server serverr = new server();
serverr.start(4000);
}
}
Клиент
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(socket.getInputStream());
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
String alinacak = "";
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Lütfen isminizi giriniz: ");
name = scan.nextLine();
while (!line.equals("Over"))
{
try
{
System.out.print(name+" -> ");
line = scan.nextLine();
out.writeUTF(line);
System.out.println(input.readUTF());
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 4000);
}
}
Я хочу создать простую программу чата с использованием сокетного программирования на Java. Нет проблем в общении между серверами и клиентами. Но я хочу сделать так, чтобы я хотел, чтобы сообщения приходили от других клиентов в любом клиенте, таком как приложения чата. Где я не прав и как мне это сделать?