[英]How should I run a Server/Client Code?
i just started writing my first Server/Client code and its a simple chat program, but i dont know how should I run the Code !我刚刚开始编写我的第一个服务器/客户端代码及其一个简单的聊天程序,但我不知道应该如何运行代码!
there is a.class file named Server Side, and a.class file named clientSide, are they supposed to be in different projects?有一个名为Server Side 的.class 文件和一个名为clientSide 的.class 文件,它们应该在不同的项目中吗? how should I run it so they both have a connection together?我应该如何运行它以使它们都连接在一起? thanks already,following is a part of the codes已经谢谢了,以下是代码的一部分
public void runServer()
{
try {
server = new ServerSocket();
while(true)
{
try
{
connection = server.accept();
try{
output = new ObjectOutputStream(connection.getOutputStream()) ;
output.flush();
input = new ObjectInputStream(connection.getInputStream()) ;
sendData(message) ;
do
{
try{
message = (String) input.readObject() ;
System.out.println(message);
}catch(Exception e)
{
e.printStackTrace() ;
}
}while(!message.equals("end"));
}catch(EOFException e)
{
e.printStackTrace() ;
}
}catch(IOException e)
{
e.printStackTrace() ;
}
finally {
try{
output.close();
input.close();
connection.close() ;
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}catch(Exception e )
{
e.printStackTrace();
}
}
and here's the clientSide:这是客户端:
public void runClient()
{
try{
connect() ;
}catch(Exception e)
{
e.printStackTrace();
}
try{
output = new ObjectOutputStream(client.getOutputStream()) ;
output.flush() ;
input = new ObjectInputStream(client.getInputStream()) ;
}catch(IOException e)
{
e.printStackTrace() ;
}
do
{
try{
message = (String) input.readObject() ;
System.out.println(message);
}catch(Exception e)
{e.printStackTrace();}
}while(!message.equals("end")) ;
}
public void connect() throws UnknownHostException, IOException
{
client = new Socket(InetAddress.getByName(chatServer),12345) ;
}
First run the server首先运行服务器
java Server java 服务器
Then run the client:然后运行客户端:
java Client java客户端
But I do not see your server bound to the port 12345. The client will try to connect to the server on the port 12345 because of the statement但是我没有看到你的服务器绑定到12345端口。客户端会尝试连接到12345端口的服务器,因为语句
client = new Socket(InetAddress.getByName(chatServer),12345) ;
If the ports do not match, the connection will not be established.如果端口不匹配,则不会建立连接。
To bind the server to the port 12345 try this:要将服务器绑定到端口 12345,请尝试以下操作:
server = new ServerSocket(12345);
instead of the default constructor.而不是默认的构造函数。
There is a very nice tutorial where you have all described:有一个非常好的教程,你们都描述了:
http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html
You should do 2 files one for server one for client,in two distinct packages:client and server.您应该为客户端执行 2 个文件,一个用于服务器,一个用于客户端,位于两个不同的包中:客户端和服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.