-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTcpSocket.java
More file actions
38 lines (32 loc) · 1.33 KB
/
TcpSocket.java
File metadata and controls
38 lines (32 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TcpSocket {
private DatagramSocket udpSocket;
private void setTimeout(int mls){ try { udpSocket.setSoTimeout(mls); } catch (Exception e){ e.printStackTrace(); }}
public TcpSocket(){ try{ udpSocket=new DatagramSocket(); } catch (Exception e){e.printStackTrace();} }
public TcpSocket(int port){ try{ udpSocket=new DatagramSocket(port); } catch (Exception e){e.printStackTrace();} }
public TcpPacket receive()
{
byte[] recvBuffer=new byte[14];
TcpPacket pkt=new TcpPacket(new DatagramPacket(recvBuffer,recvBuffer.length));
try{ udpSocket.receive(pkt.getUdpPacket()); }
catch (Exception e) { e.printStackTrace(); }
pkt.unPack(); return pkt;
}
public void send(TcpPacket pkt)
{
try{ udpSocket.send(pkt.getUdpPacket()); }
catch (Exception e) { e.printStackTrace(); }
}
public TcpPacket receiveWithoutWait()
{
setTimeout(10);
byte[] recvBuffer=new byte[14];
TcpPacket pkt=new TcpPacket(new DatagramPacket(recvBuffer,recvBuffer.length));
try{ udpSocket.receive(pkt.getUdpPacket()); }
catch (Exception e) { setTimeout(0); return null; }
pkt.unPack(); setTimeout(0);
return pkt;
}
public void close(){ udpSocket.close(); }
}