标签:stream 建立连接 break tin system java address 服务器端 out
访问控制修饰符:
类别 | 范围 | 使用对象 |
---|---|---|
default | 同一包内可见 | 类、接口、变量、方法 |
private | 同一类内可见 | 不能修饰类 |
public | 对所有类可见 | 类、接口、变量、方法 |
protected | 同一包内和所有子类可见 | 变量、方法、不能修饰类(外部类) |
访问控制和继承:
网络编程:
利用socket建立连接的过程:
连接建立后,通过使用I/O流进行通信,每一个socket有一个输出流和输入流,客户端的输出流连接到服务端的输入流,客户端的输入流连接到服务器端的输出流
例子:
// 文件名 GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
//通过命令行来传入服务端的主机名以及端口
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
Socket client = new Socket(serverName, port);
System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
//利用输出流,向服务端发送信息
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
//利用输入流,从服务端读取信息
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("服务器响应: " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// 文件名 GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.run();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
标签:stream 建立连接 break tin system java address 服务器端 out
原文地址:https://www.cnblogs.com/share-sjb/p/9146179.html