gvsu/cs654/proj1/KaZaServer.java
josh 321043b407 processing opcodes, reading and storing file descriptions
git-svn-id: svn://anubis/gvsu@36 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-03-08 21:30:59 +00:00

126 lines
3.8 KiB
Java

import java.io.*;
import java.net.*;
import java.util.*;
public class KaZaServer implements Runnable
{
public static final int LISTEN_PORT = 3442;
private ServerSocket m_serverSocket;
private HashMap<String, ClientInfo> m_clientData;
public void run()
{
try {
m_serverSocket = new ServerSocket(LISTEN_PORT);
/* porcess connection requests */
for (;;)
{
Socket clientSocket = m_serverSocket.accept();
Thread thread = new Thread(new ClientHandler(clientSocket));
thread.start();
}
} catch (IOException ioe) {
System.out.println("KaZaServer: IO Exception!");
ioe.printStackTrace();
return;
}
}
public void close()
{
}
public String[] getClientList()
{
Set<String> s;
synchronized (m_clientData)
{
s = m_clientData.keySet();
}
return (String[]) s.toArray();
}
private class ClientInfo
{
String userName = "Anonymous";
HashMap<String, String> files = new HashMap<String, String>();
}
private class ClientHandler implements Runnable
{
private Socket m_socket;
private String m_clientIP;
ClientInfo m_clientInfo;
public ClientHandler(Socket socket)
{
m_socket = socket;
m_clientIP = m_socket.getInetAddress().getHostAddress();
synchronized (m_clientData)
{
if (!m_clientData.containsKey(m_clientIP))
{
m_clientData.put(socket.getInetAddress().getHostAddress(),
new ClientInfo());
}
m_clientInfo = m_clientData.get(m_clientIP);
}
}
public void run()
{
try
{
BufferedReader br = new BufferedReader(
new InputStreamReader(
m_socket.getInputStream()));
/* loop processing client messages */
for (;;)
{
String inLine = br.readLine();
StringTokenizer tokens = new StringTokenizer(inLine);
if (!tokens.hasMoreTokens())
continue;
String opCode = tokens.nextToken();
opCode.toUpperCase();
if (opCode.equals("HELO"))
{
/* user is announcing his or her username */
synchronized (m_clientData)
{
m_clientInfo.userName = inLine.substring(5);
}
}
else if (opCode.equals("DESC"))
{
/* user is giving us a description of a file */
String fileName = inLine.substring(5);
String fileDesc = "";
boolean first = true;
for (;;)
{
String descLine = br.readLine();
if (descLine.equals("."))
break;
if (!first)
fileDesc += "\n";
fileDesc += descLine;
first = false;
}
synchronized (m_clientData)
{
m_clientInfo.files.put(fileName, fileDesc);
}
}
}
} catch (Exception e) { }
}
}
}