複数のクライアントからの要求を受け入れ、2つのクライアント間で双方向のチャットを開始する単純なTCPクライアント/サーバプログラムを作成したいと思います。他のクライアントの応答を待たずに
私はいくつかのコードを書かれているし、次のTCPサーバとJavaの2つのクライアント間のチャット
//Server Side code
public class ServerThread extends Thread
{
private StringProperty clientname;
private StringProperty clientIP;
private IntegerProperty clientport;
private Socket clientsock;
File file;
public ServerThread(Socket cs,String name)
{
clientname=new SimpleStringProperty(name);
setClientsock(cs);
clientIP=new SimpleStringProperty(cs.getInetAddress().getHostAddress().toString());
clientport=new SimpleIntegerProperty(cs.getPort());
this.start();
}
public void run()
{
System.out.println("Now i am started:");
try
{
System.out.println("clientname.getValue() "+clientname.getValue());
BufferedReader infromclient = new BufferedReader(new InputStreamReader(clientsock.getInputStream()));
file=new File(clientname.getValue()+".txt");
if(!file.exists())
file.createNewFile();
while(true)
{
FileWriter writer = new FileWriter(file, true);
writer.write((char)infromclient.read());
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public StringProperty getClientname()
{
return clientname;
}
public void setClientname(String name)
{
clientname=new SimpleStringProperty(name);
}
public StringProperty getClientIP()
{
return clientIP;
}
public void setClientIP(String string)
{
this.clientIP.set(string);
}
public IntegerProperty getClientport()
{
return clientport;
}
public void setClientport(int clientport)
{
this.clientport.set(clientport);
}
public Socket getClientsock()
{
return clientsock;
}
public void setClientsock(Socket clientsock)
{
this.clientsock = clientsock;
}
}
クライアント側のコード
public class Cleint {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket clientsock=new Socket("127.0.0.1",5055);
System.out.println("Conected with server:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
BufferedReader infromServer=new BufferedReader(new InputStreamReader(clientsock.getInputStream()));
PrintWriter out=new PrintWriter(clientsock.getOutputStream(),true);
String fromServer = infromServer.readLine();
System.out.println("Server says: " + fromServer);
String string=in.readLine();
out.println(string);
while(true)
{ System.out.print("Enter Msg:");
string=in.readLine();
// javax.swing.JOptionPane.showInputDialog(null, "Client Enter value");
out.println(string);
// System.out.println("In client loop");
fromServer = infromServer.readLine();
System.out.println("Server says: " + fromServer);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
あなたの質問は? – UnholySheep
ありがとう@ UnholySheep私は@ Raja Hammad Farooqの解決策を見つけた –