java 发送tcp_Java TCP发送与接收
IP地址?端口號(hào)?主機(jī)名?
什么是Socket?
什么是UDP?
什么是TCP?
UDP和TCP區(qū)別?
以上問(wèn)題請(qǐng)自行百度,有標(biāo)準(zhǔn)解釋,此處不再贅述,直接上干貨!
實(shí)例:
發(fā)送端:
public class TCPClient {
public static void main(String[] args) throws IOException {
//創(chuàng)建Socket對(duì)象
Socket s = new Socket(InetAddress.getByName("127.0.0.1"),10086);
//獲取輸出流對(duì)象
OutputStream os = s.getOutputStream();
//發(fā)送數(shù)據(jù)
String str = "This TCP,im comming";
os.write(str.getBytes());
//釋放
s.close();
}
}
接收端:
public class TCPServer {
public static void main(String[] args) throws IOException {
//創(chuàng)建Socket對(duì)象
ServerSocket ss = new ServerSocket(10086);
//監(jiān)聽(tīng)(阻塞)
Socket s = ss.accept();
//獲取輸入流對(duì)象
InputStream is = s.getInputStream();
//獲取數(shù)據(jù)
byte[] bys = new byte[1024];
int len;
len = is.read(bys);
//輸出數(shù)據(jù)
InetAddress address = s.getInetAddress();
System.out.println("sender:"+address);
System.out.println(new String(bys,0,len));
//釋放
s.close();
/*
* 說(shuō)明:
* 當(dāng)你訪(fǎng)問(wèn)百度的時(shí)候,退出了,它的服務(wù)就關(guān)了嗎? 不關(guān),還會(huì)繼續(xù)監(jiān)聽(tīng)
*/
}
}
測(cè)試:
先運(yùn)行server服務(wù)端,開(kāi)啟監(jiān)聽(tīng)
在開(kāi)啟發(fā)送端
服務(wù)器就會(huì)監(jiān)聽(tīng)到發(fā)送端發(fā)來(lái)的消息
最后附上API 文檔說(shuō)明,防止有些人看不懂代碼
總結(jié)
以上是生活随笔為你收集整理的java 发送tcp_Java TCP发送与接收的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 无品牌限制的多屏协同和远程控制的软件无品
- 下一篇: 不想下班背电脑下班不想带电脑