1. 程式人生 > >使用TCP協議編寫一個網絡程序.....................

使用TCP協議編寫一個網絡程序.....................

9.png accept nbsp img java.net div sys 協議 分享

技術分享圖片

package tCP;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClient {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new TCPClient1().connect();


}

}
class TCPClient1{
private static final int PORT = 8002;
public void connect() throws Exception{
Socket client = new Socket(InetAddress.getLocalHost(), PORT);
InputStream is = client.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
client.close();
}
}

package tCP;


import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new TCPServer1().listen();

}

}

class TCPServer1{
private static final int PORT = 8002;
public void listen() throws Exception{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket client = serverSocket.accept();
OutputStream os = client.getOutputStream();
System.out.println("開始與客戶端交互數據");
String str = "Hello,world";
os.write(str.getBytes());
System.out.println("結束與客戶端交互數據");
os.close();
client.close();
}
}

技術分享圖片

技術分享圖片

使用TCP協議編寫一個網絡程序.....................