Socket方法
getInetAddress(); 远程服务端的IP地址
getPort(); 远程服务端的端口
getLocalAddress() 本地客户端的IP地址
getLocalPort() 本地客户端的端口
getInputStream(); 获得输入流
getOutStream(); 获得输出流
Socket状态
isClosed(); //连接是否已关闭,若关闭,返回true;否则返回false
isConnect(); //如果曾经连接过,返回true;否则返回false
isBound(); //如果Socket已经与本地一个端口绑定,返回true;否则返回false
socket.setSoTimeout(10000);
Socket socket = new Socket("127.0.0.1",12345);
用下面方法代替上面方法
Socket socket1 = new Socket();
socket1.connect(new InetSocketAddress("127.0.0.1",12345),timeout);
package basic_socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Scanner;
public class SocketTest {
public static void main(String[] args)
{
try {
Socket socket = new Socket("127.0.0.1",12345);
InputStream inputStream = socket.getInputStream();
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine())
{
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package basic_socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketTest {
public static void main(String ars[])
{
try {
ServerSocket serverSocket = new ServerSocket(12345);
while (true)
{
Socket socket =serverSocket.accept();
Thread client = new Client(socket);
client.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client extends Thread
{
private Socket socket =null;
public Client(Socket socket)
{
this.socket =socket;
}
public void run() {
try{
System.out.println("新连接:"+socket.getInetAddress()+":"+socket.getPort());
Thread.sleep(10000);
}catch(Exception e){e.printStackTrace();}finally{
try{
System.out.println("关闭连接:"+socket.getInetAddress()+":"+socket.getPort());
if(socket!=null)socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}