实现网络连接,最基本的就两步:
1,
客户端:
Socket socket=new Socket("IP",端口);
2,
服务器:
ServerSocket serverSocket=new ServerSocket(端口);
serverSocket.accept();
通讯的话使用输入输出流。
将数据传入流中
OutputStream output=sockt.getOutputStream();
DataOutputStream out=new DataOutputStream(output);
out.write("你好!");
将数据从流中取出。
InputStream input= sockt.getOutPutStream();
DataInputStream in=sockt.getDataInputStream();
out.read();u
下面看代码:
服务端
1
package com.hello.MrC;
2
3
import java.net.*;
4
import java.io.*;
5
/**
6
* 服务端
7
* @author MyPC
8
*
9
*/
10
public class Servers_a extends Thread {
11
12
private ServerSocket serverSocket;
13
14
public Servers_a(int port) throws IOException{
15
serverSocket=new ServerSocket(port);
16
// serverSocket.setSoTimeout(10000);//启用/禁用带有指定超时值的 SO_TIMEOUT,以毫秒为单位。
17
}
18
19
public void run(){
20
while(true){
21
try{
22
System.out.println("等待来自客户端的端口:"+serverSocket.getLocalPort()+"...");//getLocalPort():返回此套接字绑定到的本地端口。
23
Socket server=serverSocket.accept();
24
System.out.println("正在连接:"+server.getRemoteSocketAddress());//getRemoteSocketAddress():返回此套接字绑定的端点的地址,如果尚未绑定则返回 null
25
DataInputStream in=new DataInputStream(server.getInputStream());//getInputStream():返回此套接字的输入流。
26
System.out.println(in.readUTF());
27
DataOutputStream out=new DataOutputStream(server.getOutputStream());//getOutputStream():返回此套接字的输出流。
28
out.writeUTF("谢谢连接:"+server.getLocalSocketAddress()+"\n再见!");
29
server.close();
30
}catch(SocketTimeoutException s){
31
System.out.println("Socket时间超时!");
32
break;
33
}catch(IOException e){
34
e.printStackTrace();
35
break;
36
}
37
}
38
}
39
public static void main(String[] args){
40
// int port=Integer.parseInt(args[0]);
41
int port=49797;
42
try{
43
Thread t=new Servers_a(port);
44
t.start();
45
}catch(IOException e){
46
e.printStackTrace();
47
}
48
}
49
50
}
51
客户端:
1
package com.hello.MrC;
2
3
import java.net.*;
4
import java.io.*;
5
/**
6
* 客户端
7
* @author MyPC
8
*
9
*/
10
11
public class Khd_a {
12
13
public static void main(String[] args){
14
// String serverName=args[0];
15
String serverName="127.0.0.1";
16
int port=49797;
17
int i=0;
18
try{
19
System.out.println("连接的IP:"+serverName+"\n端口号"+port);
20
21
Socket client=new Socket(serverName,port);
22
System.out.println("连接:"+client.getRemoteSocketAddress());//getRemoteSocketAddress():返回此套接字绑定的端点的地址,如果尚未绑定则返回 null
23
24
OutputStream outToServer=client.getOutputStream();
25
DataOutputStream out=new DataOutputStream(outToServer);
26
out.writeUTF("你好,我来自:"+client.getLocalSocketAddress());//以UTF-8格式将数据输出到流中
27
InputStream inFromServer=client.getInputStream();
28
DataInputStream in=new DataInputStream(inFromServer);
29
30
System.out.println("服务器说:"+in.readUTF());
31
client.close();
32
}catch(IOException e){
33
e.printStackTrace();
34
}
35
36
}
37
}
38