java聊天室代码百度云 java聊天程序代码( 五 )


socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; iresponse.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中 , 有两个个参数时的构造方法,第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; iresponse.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request , 用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket , 用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//创建服务器端数据输入输出流 , 用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息,并显示

推荐阅读