top of page
게시판 게시물
080927kdy
2024년 2월 18일
In 소스 코드 제출
def solution(k, dungeons): answer = -1 whole_case = [] for a in range(len(dungeons)): A = k Al = [] Al.append(a) if A >= dungeons[a][0]: A -= dungeons[a][1] for b in range(len(dungeons) - 1): B = A Bl = Al Bl.append(b) if b in Bl: whole_case.append(len(Bl) - 1) else: if B >= dungeons[b][0]: B -= dungeons[b][1] for c in range(len(dungeons) - 2): C = B Cl = Bl Cl.append(c) if c in Cl: whole_case.append(len(Cl) - 1) else: if C >= dungeons[c][0]: C -= dungeons[c][1] for d in range(len(dungeons) - 3): D = C Dl = Cl Dl.append(d) if d in Dl: whole_case.append(len(Dl) - 1) else: if D >= dungeons[d][0]: D -= dungeons[d][1] for e in range(len(dungeons) - 4): E = D El = Dl El.append(e) if e in El: whole_case.append(len(El) - 1) else: if E >= dungeons[e][0]: E -= dungeons[e][1] for f in range(len(dungeons) - 5): F = E Fl = El Fl.append(f) if f in Fl: whole_case.append(len(Fl) - 1) else: if F >= dungeons[f][0]: F -= dungeons[f][1] for g in range(len(dungeons) - 6): G = F Gl = Fl Gl.append(g) if g in Gl: whole_case.append(len(Gl) - 1) else: if G >= dungeons[g][0]: G -= dungeons[g][1] for h in range(len(dungeons) - 7): H = G Hl = Gl Hl.append(h) if h in Hl: whole_case.append(len(Hl) - 1) else: if H >= dungeons[h][0]: H -= dungeons[h][1] whole_case.append(len(Hl)) else: whole_case.append(len(Hl) - 1) else: whole_case.append(len(Gl) - 1) else: whole_case.append(len(Fl) - 1) else: whole_case.append(len(El) - 1) else: whole_case.append(len(Dl) - 1) else: whole_case.append(len(Cl) - 1) else: whole_case.append(len(Bl) - 1) else: whole_case.append(len(Al) - 1) print(whole_case) return answersolution(80, [[80,20],[50,40],[30,10]])
0
0
1
080927kdy
2024년 1월 28일
In 소스 코드 제출
# n, m, k = map(int, input().split())# ls = []# for i in range(m):# v = []# for j in range(n):# v.append(0)# ls.append(v)# for i in range(k):# x1, y1, x2, y2 = map(int, input().split())# for j in range(x1, x2):# for k in range(y1, y2):# ls[j][k] = 1# lsp = []# for i in range(m+2):# v = []# for j in range(n+2):# v.append(0)# lsp.append(v)#### for i in range(m+2):# for j in range(n+2):# if i == 0 or i == m+1 or j == 0 or j == n+1:# lsp[i][j] = 1# else:# lsp[i][j] = ls[i-1][j-1]## ls = lsp# for i in range(m+2):# for j in range(n+2):# print(ls[i][j], end=' ')# print()## cnt = []## def find(x, y, z):# global m,n,ls, cnt# if ls[x][y] == 0:# ls[x][y] = 1# cnt[z] += 1# find(x + 1, y, z)# find(x, y + 1, z)# find(x - 1, y, z)# find(x, y - 1, z)### c = 0### for i in range(m+2):# for j in range(n+2):# if ls[i][j] == 0:# cnt.append(0)# find(i, j, c)# c += 1## print(c)# lss = []# for i in range(c):# lss.append(cnt[i])## lss.sort()# for i in range(c):# print(lss[i], end=' ')# import sys# limit_number = 1500000# sys.setrecursionlimit(limit_number)## n, m, k = map(int, input().split())# ls = []# r = 0# for i in range(m):# v = []# for j in range(n):# v.append(-1)# ls.append(v)# for i in range(k):# x1, y1, x2, y2 = map(int, input().split())# if i == 0:# r = x1# for j in range(x1, x2):# for k in range(y1, y2):# ls[j][k] = -2# lsp = []# for i in range(m+2):# v = []# for j in range(n+2):# v.append(-1)# lsp.append(v)#### for i in range(m+2):# for j in range(n+2):# if i == 0 or i == m+1 or j == 0 or j == n+1:# lsp[i][j] = -2# else:# lsp[i][j] = ls[i-1][j-1]## ls = lsp### cnt = []## def find(x, y, z):# global m,n,ls, cnt# if ls[x][y] == -1:# ls[x][y] = cnt[z]# cnt[z] += 1# find(x + 1, y, z)# find(x, y + 1, z)# find(x - 1, y, z)# find(x, y - 1, z)#### c = 0### for i in range(m+2):# for j in range(n+2):# if ls[i][j] == -1:# cnt.append(0)# find(i, j, c)# c += 1## # for i in range(m+2):# # for j in range(n+2):# # print(ls[i][j], end=' ')# # print()## print(c)# lss = []# for i in range(c):# lss.append(cnt[i])## lss.sort()# for i in range(c):# print(lss[i], end=' ')class solve: def __init__(self): self.box = [] self.m, self.n = map(int, input().split()) for i in range(self.n): s = input().split() self.box.append(s) for i in range(self.n): for j in range(self.m): self.box[i][j] = int(self.box[i][j]) self.queue = [] for i in range(self.m*self.n+1): self.queue.append([-1, -1, -1]) self.start = 0 self.end = 0 self.to_be_end = True for i in range(self.n): for j in range(self.m): if self.box[i][j] == 1: self.queue[self.end][0] = i self.queue[self.end][1] = j self.queue[self.end][2] = -1 self.end += 1 self.box[i][j] = 0 if self.end == 0: self.to_be_end = False def find(self): x = self.queue[self.start][0] y = self.queue[self.start][1] z = self.queue[self.start][2] self.box[x][y] = 1 print(self.box) self.start += 1 if 0 <= x + 1 < self.n and 0 <= y < self.m and self.box[x + 1][y] == 0: self.queue[self.end][0] = x + 1 self.queue[self.end][1] = y self.queue[self.end][2] = z + 1 self.end += 1 if 0 <= x < self.n and 0 <= y + 1 < self.m and self.box[x][y + 1] == 0: self.queue[self.end][0] = x self.queue[self.end][1] = y + 1 self.queue[self.end][2] = z + 1 self.end += 1 if 0 <= x - 1 < self.n and 0 <= y < self.m and self.box[x - 1][y] == 0: self.queue[self.end][0] = x - 1 self.queue[self.end][1] = y self.queue[self.end][2] = z + 1 self.end += 1 if 0 <= x < self.n and 0 <= y - 1 < self.m and self.box[x][y - 1] == 0: self.queue[self.end][0] = x self.queue[self.end][1] = y - 1 self.queue[self.end][2] = z + 1 self.end += 1u = solve()while True: u.find() if u.to_be_end == True: print(u.queue) break
0
0
1
080927kdy
2024년 1월 14일
In 소스 코드 제출
# a = int(input())# b = 0# if a <= 500:# b = a * 70 / 100# elif 500 < a and a <= 1500:# b = 350 + (a - 500) * 40 / 100# elif 1500 < a and a <= 4500:# b = 750 + (a - 1500) * 15 / 100# elif 4500 < a and a <= 10000:# b = 1200 + (a - 4500) * 5 / 100# else :# b = 1475 + (a - 10000) * 2 / 100# print('%.0f' %b)# x = input()# s = 0# for i in range(1, len(x)):# if x[i-1] == x[i]:# s += 5# else :# s += 10# print(s + 10)# a = int(input())# sum = 0# for i in range(a):# x, y = input().split()# x = int(x)# y = int(y)# n = y % x# sum += n# print(sum)# n = int(input())# m = int(input())## ls = []# check = 0# check_ls = []## for i in range(n):# v = []# for j in range(n):# v.append(0)# ls.append(v)## for i in range(m):# x, y = map(int, input().split())# ls[x-1][y-1] = 1# ls[y-1][x-1] = 1### def f(x):# global check# for k in range(n):# if ls[x][k] == 1:# if check_ls.__contains__(x) == False or check_ls.__contains__(k) == False:# check += 1# check_ls.append(x)# check_ls.append(k)# f(k)## f(0)# print(check)# check = 1# ls = []## for i in range(7):# s = input().split()# v = []# for j in range(7):# v.append(int(s[j]))# ls.append(v)##### def find(x, y, c):# ls[x][y] = 0# global check# if x >= 1:# if ls[x-1][y] == c:# check += 1# find(x-1, y, c)# if x <= 5:# if ls[x+1][y] == c:# check += 1# find(x+1, y, c)# if y >= 1:# if ls[x][y-1] == c:# check += 1# find(x, y-1, c)# if y <= 5:# if ls[x][y+1] == c:# check += 1# find(x, y+1, c)### s = 0## for i in range(7):# for j in range(7):# if ls[i][j] != 0:# find(i, j, ls[i][j])# if check >= 3:# s += 1# check = 1## print(s)# A = 0## ls = []# n = int(input())# for i in range(n):# v = []# for j in range(n):# v.append(100)# ls.append(v)## xK, yK = map(int, input().split())# xK -= 1# yK -= 1# x0, y0 = map(int, input().split())# x0 -= 1# y0 -= 1## def f(x, y, cnt):# global A# if A == 0:# if x !=x0 or y != y0:# ls[x][y] = cnt# if x >= 2 and y >= 1:# if ls[x-2][y-1] > cnt+1:# f(x-2, y-1, cnt+1)## if x >= 1 and y >= 2:# if ls[x - 1][y - 2] > cnt + 1:# f(x - 1, y - 2, cnt+1)## if x < n-2 and y < n-1:# if ls[x + 2][y + 1] > cnt + 1:# f(x + 2, y + 1, cnt+1)## if x < n-1 and y < n-2:# if ls[x + 1][y + 2] > cnt + 1:# f(x + 1, y + 2, cnt+1)## if x < n-1 and y >= 2:# if ls[x - 1][y - 2] > cnt + 1:# f(x - 1, y - 2, cnt+1)## if x < n-2 and y >= 1:# if ls[x + 2][y - 1] > cnt + 1:# f(x + 2, y - 1, cnt+1)## if x >= 1 and y < n-2:# if ls[x - 1][y + 2] > cnt + 1:# f(x - 1, y + 2, cnt+1)## if x >= 2 and y < n-1:# if ls[x - 2][y + 1] > cnt + 1:# f(x - 2, y + 1, cnt+1)# else:# A += 1# ls[x0][y0] = cnt# cnt = 0# else:# if cnt == 0:# for i in range(n):# for j in range(n):# ls[i][j] = 0# elif x != x0 or y != y0 and cnt < ls[x0][y0]:# if x >= 2 and y >= 1:# f(x - 2, y - 1, cnt + 1)## if x >= 1 and y >= 2:# f(x - 1, y - 2, cnt + 1)## if x < n - 2 and y < n - 1:# f(x + 2, y + 1, cnt + 1)## if x < n - 1 and y < n - 2:# f(x + 1, y + 2, cnt + 1)## if x < n - 1 and y >= 2:# f(x - 1, y - 2, cnt + 1)## if x < n - 2 and y >= 1:# f(x + 2, y - 1, cnt + 1)## if x >= 1 and y < n - 2:# f(x - 1, y + 2, cnt + 1)## if x >= 2 and y < n - 1:# f(x - 2, y + 1, cnt + 1)# elif x == x0 and y == y0:# ls[x0][y0] = cnt# cnt = 0## f(xK, yK, 0)## print(ls[x0][y0])#ls = []n = int(input())for i in range(n): v = [] for j in range(n): v.append(668) ls.append(v)xK, yK = map(int, input().split())xK -= 1yK -= 1x0, y0 = map(int, input().split())x0 -= 1y0 -= 1def f(x, y, cnt): if x !=x0 or y != y0: ls[x][y] = cnt if x >= 2 and y >= 1: if ls[x-2][y-1] > cnt+1: f(x-2, y-1, cnt+1) if x >= 1 and y >= 2: if ls[x - 1][y - 2] > cnt + 1: f(x - 1, y - 2, cnt+1) if x < n-2 and y < n-1: if ls[x + 2][y + 1] > cnt + 1: f(x + 2, y + 1, cnt+1) if x < n-1 and y < n-2: if ls[x + 1][y + 2] > cnt + 1: f(x + 1, y + 2, cnt+1) if x < n-1 and y >= 2: if ls[x + 1][y - 2] > cnt + 1: f(x + 1, y - 2, cnt+1) if x < n-2 and y >= 1: if ls[x + 2][y - 1] > cnt + 1: f(x + 2, y - 1, cnt+1) if x >= 1 and y < n-2: if ls[x - 1][y + 2] > cnt + 1: f(x - 1, y + 2, cnt+1) if x >= 2 and y < n-1: if ls[x - 2][y + 1] > cnt + 1: f(x - 2, y + 1, cnt+1) else: if ls[x0][y0] > cnt: ls[x0][y0] = cntf(xK, yK, 0)print(ls[x0][y0])
0
0
3
080927kdy
2024년 1월 06일
In 소스 코드 제출
# # 변수 status# # empty## class queue:# def __init__(self):# self.status = False# self.Q = []# for i in range(5):# self.Q.append(' ')# self.f = 0# self.r = 0## def push(self, m):# if self.r != self.f or self.status != True:# self.Q[self.r] = m# self.r += 1# self.r %= 5# self.status = True## def pop(self):# if self.r != self.f or self.status != False:# self.Q[self.f] = ' '# self.f += 1# self.f %= 5# self.status = False## def view(self):# v = [0, 0, 0, 0, 0]# for i in range(5):# v[i] = self.Q[(i+self.f)%5]# print(v)## def is_full(self):# if self.r == self.f and self.status == True:# print('True')# else:# print('False')#### def is_empty(self):# if self.r == self.f and self.status == False:# print('True')# else:# print('False')### k = queue()## while(True):# s = input()# if s.__contains__('push'):# k.push(int(s[5:-1]))# elif s.__contains__('pop'):# k.pop()# elif s.__contains__('view'):# k.view()# elif s.__contains__('is_full'):# k.is_full()# elif s.__contains__('is_empty'):# k.is_empty()###n = int(input())v = [0]while True: if v[0] == 0: v[0] = 1 else: v.append(0) k = v k.reverse() s = '' for i in range(len(k)): s += str(k[i]) s = int(s) if s % n == 0: print(s) break if s > 4294967295: print(0)
0
0
2
080927kdy
2023년 12월 17일
In 소스 코드 제출
# class school:# def __init__(self, x, y):# print('This is Initialize Function')# # self: 클래스 내에서 자유롭게 가져다가 쓸 수 있도록 하는 마법의 단어# self.x = x# self.y = y## def vol(self):# print('VOL')# print(self.x + self.y)## a,b = map(int, input().split())## x = school(a, b)# x.vol()'''FILO: First In, Last Outif condition {}else {}List = [0, 0, 0, 0, 0] # stack'''# 입력값에 0 없음# class stack:# def __init__(self, N):# self.N = N# self.list = []# for i in range(self.N):# self.list.append(0)# self.top = -1## def push(self, x):# if self.top < self.N -1:# self.list[self.top+1] = x# self.top += 1# else:# print("범위 넘어감")## def pop(self):# if self.top > -1:# self.list[self.top] = 0# self.top -= 1# else:# print("범위 넘어감")## def view(self):# for i in range(self.N):# if self.list[self.N-1-i] != 0:# print(self.list[self.N-1-i])# def is_empty(self):# num = 0# for i in range(self.N):# if self.list[i] == 0:# num += 1# if num == self.N:# print('Y')# else:# print('N')# def is_full(self):# num = 0# for i in range(self.N):# if self.list[i] == 0:# num += 1# if num == 0:# print('Y')# else:# print('N')#### n = int(input())# k = stack(n)## # for i in range(n):# while True:# x = input()# a1 = -1# for i in x:# if i == '(':# break# a1 += 1# if x[a1+2:-1] != '':# num = int(x[a1+2:-1])## s = x[:a1+1]# if s == "push":# k.push(num)# elif s == "pop":# k.pop()# elif s == "is_empty":# k.is_empty()# elif s == "is_full":# k.is_full()# elif s == "view":# k.view()class stack: def __init__(self): self.N = 205 self.printlist = [] self.list = [] for i in range(self.N): self.list.append(1.1) self.top = -1 self.printnum = 0 def push(self, x): if self.top < self.N -1: self.list[self.top+1] = x self.top += 1 def pop(self): if self.top > -1: self.list[self.top] = 0 self.top -= 1 def Top(self): if self.list[self.top] == 1.1: self.printlist.append(-1) self.printnum += 1 else: self.printlist.append(self.list[self.top]) self.printnum += 1 def size(self): self.printlist.append(self.top+1) self.printnum += 1 def empty(self): if self.top + 1 == 0: self.printlist.append("true") self.printnum += 1 else: self.printlist.append("false") self.printnum += 1n = int(input())k = stack()for i in range(n): x = input() if x.__contains__('push'): num = int(x[6:-2]) k.push(num) elif x.__contains__('pop'): k.pop() elif x.__contains__('top') == True: k.Top() elif x.__contains__('size') == True: k.size() elif x.__contains__("empty") == True: k.empty()for i in range(k.printnum): print(k.printlist[i])# string = 'Hello World'# print(string.__contains__('Hello'))# string = 'push( 5523423232355 )'# print(string[6:-2])
0
0
1
080927kdy
2023년 12월 10일
In 소스 코드 제출
# print("Hello World")# print("\"Hello World\"")# print("print(\"Hello\\nWorld\")")# a = input()# b = input()## print(int(a))# print(int(b))# a, b = input().split()# print(b, end=' ')# print(a)# a, b, c = input().split('.')# print(c, end='-')# print(b, end='-')# print(a)# a, b, c = input().split(':')# print(b)# a, b = input().split()# print(int(a)+int(b))# a = input()# print(ord(a))# a, b = map(float, input().split())# print(a*b)# a = int(input())# if 90 <= a <= 100:# print('A')# if 70<= a < 90:# print('B')# if 40 <= a <70:# print('C')# if 0 <= a < 40:# print('D')# a = int(input())# for i in range(a):# print(a-1-i)# s = 0# a = int(input())# for i in range(1, a+1):# if i % 2 == 0:# s += i# print(s)# a, b = map(int, input().split())# print(a+b, a-b, a*b, a//b, a%b, format(a/b, ".2f"), end='\n')# a = float(input())# print(format(a, '.2f'))# a = int(input())# # x = 1# # s = 0# # while True:# # s += x# # if s >= a:# # break# # x += 1# ## # print(x)# a, d, n = map(int, input().split())# print(a+d*(n-1))# a = int(input())# x= []# y = []# k = input().split()# for i in range(a):# x.append(int(k[i]))## for i in range(1, 24):# s= 0# for j in range(a):# if x[j] == i:# s += 1## y.append(s)## for i in range(23):# print(y[i], end=' ')# x = []# a = int(input())# k = input().split()# for i in range(a):# x.append(int(k[i]))## m = x[0]# for i in range(a):# if x[i] < m:# m = x[i]## print(m)# q = []# for i in range(19):# x = input().split()# q.append(x)## a = int(input())# for i in range(a):# x1, y1 = map(int, input().split())# x1 -= 1# y1 -=1# for j in range(19):# if int(q[x1][j]) == 0:# q[x1][j] = 1# else:# q[x1][j] = 0## for i in range(19):# if int(q[i][y1]) == 0:# q[i][y1] = 1# else:# q[i][y1] = 0### for i in range(19):# for j in range(19):# print(q[i][j], end=' ')# print()# q = []# h, w = map(int, input().split())# for i in range(h):# v = []# for j in range(w):# v.append(0)# q.append(v)# n = int(input())# for i in range(n):# l, d, x, y = map(int, input().split())# x -= 1# y -= 1# if d == 0:# for j in range(y, y+l):# q[x][j] = 1# else:# for k in range(x, x+l):# q[k][y] = 1## for i in range(h):# for j in range(w):# print(q[i][j], end=' ')# print()# q = []# for i in range(10):# v = input().split()# x = []# for j in range(10):# x.append(int(v[j]))# q.append(x)## d = 0# #d가 1면 x방향, 0이면 y방향# x = 1# y = 1# #x, y는 각각 개미의 위치. x가 i랑 같은 줄# while True:# if q[x][y] == 2:# q[x][y] = 9# break# elif q[x+1][y] == 1 and q[x][y+1] == 1:# q[x][y] = 9# break# else:# q[x][y] = 9# if d == 1:# if q[x+1][y] != 1:# if q[x-1][y+1] == 1 and q[x][y+1] != 1:# y += 1# d = 0# else:# x += 1# else:# y += 1# d = 0# else:# if q[x][y+1] != 1:# y += 1# else:# x += 1# d = 1# ## # for i in range(10):# # for j in range(10):# # print(q[i][j], end=' ')# # print('')## x = input()# #print(x[-1])# print(x.find('a')) #문자열에서 a가 처음으로 나온 위치# # print(x[3:7])## # ord# # chr# #1024 1295 1406 1407 1414 1754 1990 2721 6130 6131# a = input()# for i in a :# print("\'" + i + "\'")## b = [1,3,7,6,4]# for i in b :# print(i)# y = []# a = input()# n = len(a)# x = 0# for i in a:# y.append(a[x].lower())# if y[x] == a[x]:# y[x] = a[x].upper()# x += 1## for i in range(n):# print(y[i], end='')# a = input()# if a == 'love':# print('I love you.')a = input()n = len(a)sc = 0scc = 0for i in range(n): if a[i] == 'c' or a[i] == 'C': sc += 1 if a[i+1] == 'c' or a[i+1] == 'C': scc += 1
0
0
3
080927kdy
2022년 10월 18일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
import tkinter.font as tkFont
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
global datalist
global datanum
global downbool
while True:
if num < 17:
num += 1
txt = txtParts[num]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
#############################################################################
txt.configure(background='#c8c8c8', disabledbackground='#c8c8c8')
#############################################################################
txt.insert("end", text[1])
datalist.append([text[1], 'right', 'mgrey'])
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.config(justify='left')
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0])
datalist.append([text[0], 'left', 'grey'])
num += 1
if num + 1 <= 17:
txtParts[num]['state'] = 'normal'
txtParts[num].delete(0, END)
txtParts[num].config(justify='left')
#############################################################################
txtParts[num].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[num].insert("end", text[1])
datalist.append([text[1], 'left', 'white'])
datanum += 1
txtParts[num]['state'] = 'disabled'
txtParts[num+1]['state'] = 'normal'
txtParts[num+1].delete(0, END)
#############################################################################
txtParts[num+1].configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append(['', 'left', 'grey'])
datanum += 1
downbool = True
txtParts[num+1]['state'] = 'disabled'
num += 1
else:
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
#############################################################################
txtParts[17].configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
#############################################################################
txtParts[17].configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append(['', 'left', 'grey'])
datanum += 1
downbool = True
go_down()
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
txt = txtParts[17]
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
datanum += 1
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append([text[0] + text[1], 'left', 'grey'])
downbool = True
go_down()
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
txt.configure(background='#c8c8c8', disabledbackground='#c8c8c8')
datalist.append([text[1], 'right', 'mgrey'])
downbool = True
go_down()
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
txt.configure(background='#ececec', disabledbackground='#ececec')
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
txt.config(justify='left')
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.configure(background='#ececec', disabledbackground='#ececec')
datalist.append([text[0], 'left', 'grey'])
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
txtParts[17].configure(background='white', disabledbackground='white')
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
txtParts[17].configure(background='#ececec', disabledbackground='#ececec')
datalist.append(['', 'left', 'grey'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global updownnum
if updownnum > 0:
updownnum -= 1
for i in range(17, -1, -1):
txtParts[i]['state'] = 'normal'
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
elif datalist[i + updownnum][2] == 'mgrey':
txtParts[i].configure(background='#c8c8c8', disabledbackground='#c8c8c8')
elif datalist[i + updownnum][2] == 'white':
txtParts[i].configure(background='white', disabledbackground='white')
txtParts[i]['state'] = 'disabled'
def go_down():
global datalist
global updownnum
global datanum
global downbool
print(datanum, updownnum)
if updownnum + 18 <= datanum:
print(':' + str(updownnum))
print(';' + str(datanum) + '\n')
updownnum += 1
for i in range(0, 18):
txtParts[i]['state'] = 'normal'
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
elif datalist[i + updownnum][2] == 'white':
txtParts[i].configure(background='white', disabledbackground='white')
elif datalist[i + updownnum][2] == 'mgrey':
txtParts[i].configure(background='#c8c8c8', disabledbackground='#c8c8c8')
txtParts[i]['state'] = 'disabled'
# if downbool == True:
# txtParts[17]['state'] = 'normal'
# txtParts[17].config(justify='right')
# txtParts[17].delete(0, END)
# txtParts[17].insert("end", datalist[17 + updownnum])
# txtParts[17]['state'] = 'disabled'
# downbool = False
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x610')
c_root.title('client')
c_root.resizable(False, False)
c_root['bg'] = 'black'
root.withdraw()
start_new_thread(login, ())
frame = Frame(c_root, width=300)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
txtfont = tkFont.Font(size=10)
for i in range(0, 18):
x = Entry(chat_canvas, width=67, disabledforeground='black')
# x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black', background='#BECDFF')
x.pack()
x.configure(font=txtfont)
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=5)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=500)
message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
updownnum = 0
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
2
080927kdy
2022년 10월 11일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
import tkinter.font as tkFont
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
global datalist
global datanum
global downbool
global entrynum
while True:
if num < entrynum:
num += 1
txt = txtParts[num]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
#############################################################################
txt.configure(background='white', disabledbackground='white')
#############################################################################
txt.insert("end", text[1])
datalist.append([text[1], 'right', 'white'])
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.config(justify='left')
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0])
datalist.append([text[0], 'left', 'grey'])
num += 1
if num <= entrynum:
txtParts[num]['state'] = 'normal'
txtParts[num].delete(0, END)
txtParts[num].config(justify='left')
#############################################################################
txtParts[num].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[num].insert("end", text[1])
datalist.append([text[1], 'left', 'white'])
datanum += 1
txtParts[num]['state'] = 'disabled'
else:
txtParts[entrynum]['state'] = 'normal'
txtParts[entrynum].delete(0, END)
#############################################################################
txtParts[entrynum].configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
txt = txtParts[entrynum]
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
datanum += 1
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append([text[0] + text[1], 'left', 'grey'])
downbool = True
go_down()
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
#############################################################################
txt.configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'right', 'white'])
downbool = True
go_down()
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
txt.config(justify='left')
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append([text[0], 'left', 'grey'])
downbool = True
go_down()
txtParts[entrynum]['state'] = 'normal'
txtParts[entrynum].delete(0, END)
#############################################################################
txtParts[entrynum].configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txtParts[entrynum]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global updownnum
global entrynum
if updownnum > 0:
updownnum -= 1
for i in range(entrynum, -1, -1):
txtParts[i]['state'] = 'normal'
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
#############################################################################
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
else:
txtParts[i].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[i]['state'] = 'disabled'
def go_down():
global datalist
global updownnum
global datanum
global downbool
print(datanum, updownnum)
if updownnum + entrynum + 1 <= datanum:
print(':' + str(updownnum))
print(';' + str(datanum) + '\n')
updownnum += 1
for i in range(0, entrynum + 1):
txtParts[i]['state'] = 'normal'
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
#############################################################################
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
else:
txtParts[i].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[i]['state'] = 'disabled'
# if downbool == True:
# txtParts[17]['state'] = 'normal'
# txtParts[17].config(justify='right')
# txtParts[17].delete(0, END)
# txtParts[17].insert("end", datalist[17 + updownnum])
# txtParts[17]['state'] = 'disabled'
# downbool = False
def set_go_send(event):
global go_send
go_send = True
global entrynum
c_root = Toplevel(root)
c_root.geometry('500x610')
c_root.title('client')
c_root.resizable(False, False)
c_root['bg'] = '#BECDFF'
root.withdraw()
start_new_thread(login, ())
frame = Frame(c_root, width=300)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
txtfont = tkFont.Font(size=10)
for i in range(0, entrynum + 1):
x = Entry(chat_canvas, width=65, disabledforeground='black')
# x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black', background='#BECDFF')
x.pack()
x.configure(font=txtfont)
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=5)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=500)
message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
updownnum = 0
entrynum = 24
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
4
080927kdy
2022년 10월 11일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
import tkinter.font as tkFont
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
global datalist
global datanum
global downbool
while True:
if num < 17:
num += 1
txt = txtParts[num]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
#############################################################################
txt.configure(background='white', disabledbackground='white')
#############################################################################
txt.insert("end", text[1])
datalist.append([text[1], 'right', 'white'])
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.config(justify='left')
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0])
datalist.append([text[0], 'left', 'grey'])
num += 1
if num <= 17:
txtParts[num]['state'] = 'normal'
txtParts[num].delete(0, END)
txtParts[num].config(justify='left')
#############################################################################
txtParts[num].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[num].insert("end", text[1])
datalist.append([text[1], 'left', 'white'])
datanum += 1
txtParts[num]['state'] = 'disabled'
else:
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
#############################################################################
txtParts[17].configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
txt = txtParts[17]
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
datanum += 1
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append([text[0] + text[1], 'left', 'grey'])
downbool = True
go_down()
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
#############################################################################
txt.configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'right', 'white'])
downbool = True
go_down()
elif str(text[0]) == '[System] ':
txt.config(justify='left')
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left', 'grey'])
else:
txt.config(justify='left')
text[0].replace('☈', '').strip()
txt.delete(0, END)
#############################################################################
txt.configure(background='#ececec', disabledbackground='#ececec')
#############################################################################
datalist.append([text[0], 'left', 'grey'])
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
#############################################################################
txtParts[17].configure(background='white', disabledbackground='white')
#############################################################################
datalist.append([text[1], 'left', 'white'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global updownnum
if updownnum > 0:
updownnum -= 1
for i in range(17, -1, -1):
txtParts[i]['state'] = 'normal'
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
#############################################################################
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
else:
txtParts[i].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[i]['state'] = 'disabled'
def go_down():
global datalist
global updownnum
global datanum
global downbool
print(datanum, updownnum)
if updownnum + 18 <= datanum:
print(':' + str(updownnum))
print(';' + str(datanum) + '\n')
updownnum += 1
for i in range(0, 18):
txtParts[i]['state'] = 'normal'
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i + updownnum][0])
#############################################################################
if datalist[i + updownnum][2] == 'grey':
txtParts[i].configure(background='#ececec', disabledbackground='#ececec')
else:
txtParts[i].configure(background='white', disabledbackground='white')
#############################################################################
txtParts[i]['state'] = 'disabled'
# if downbool == True:
# txtParts[17]['state'] = 'normal'
# txtParts[17].config(justify='right')
# txtParts[17].delete(0, END)
# txtParts[17].insert("end", datalist[17 + updownnum])
# txtParts[17]['state'] = 'disabled'
# downbool = False
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x610')
c_root.title('client')
c_root.resizable(False, False)
c_root['bg'] = '#BECDFF'
root.withdraw()
start_new_thread(login, ())
frame = Frame(c_root, width=300)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
txtfont = tkFont.Font(size=10)
for i in range(0, 18):
x = Entry(chat_canvas, width=65, disabledforeground='black')
# x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black', background='#BECDFF')
x.pack()
x.configure(font=txtfont)
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=5)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=500)
# message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
updownnum = 0
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
3
080927kdy
2022년 9월 18일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
import tkinter.font as tkFont
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
# 처음일때
global datalist
global datanum
global downbool
while True:
if num < 17:
num += 1
txt = txtParts[num]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left'])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
enternum = len(text[1])//57
enterdata = []
for i in range(enternum+1):
enterdata.append(text[1][i*57:i*57+57])
for i in range(enternum+1):
if i > 0:
num += 1
datanum += 1
if num > 17:
txtParts[17].delete(0, END)
datalist.append([enterdata[i], 'right'])
downbool = True
go_down()
else:
print(i)
print(num)
print(enterdata[i])
txtParts[num]['state'] = 'normal'
txtParts[num].config(justify='right')
txtParts[num].insert("end", enterdata[i])
datalist.append([enterdata[i], 'right'])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
enternum = len(text[0]) // 57
enterdata = []
for i in range(enternum + 1):
enterdata.append(text[0][i * 57:i * 57 + 57])
for i in range(enternum + 1):
if i > 0:
num += 1
datanum += 1
if num > 17:
txtParts[17].delete(0, END)
datalist.append([enterdata[i], 'left'])
downbool = True
go_down()
else:
print(i)
print(num)
print(enterdata[i])
txtParts[num]['state'] = 'normal'
txtParts[num].config(justify='left')
txtParts[num].insert("end", enterdata[i])
datalist.append([enterdata[i], 'left'])
if num == 17:
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
enternum = len(text[0]) // 57
enterdata = []
for i in range(enternum + 1):
enterdata.append(text[0][i * 57:i * 57 + 57])
for i in range(enternum + 1):
if i > 0:
num += 1
datanum += 1
if num > 17:
txtParts[17].delete(0, END)
datalist.append([enterdata[i], 'left'])
downbool = True
go_down()
else:
print(i)
print(num)
print(enterdata[i])
txtParts[num]['state'] = 'normal'
txtParts[num].config(justify='left')
txtParts[num].insert("end", enterdata[i])
datalist.append([enterdata[i], 'left'])
txtParts[num]['state'] = 'disabled'
else:
num += 1
txtParts[num]['state'] = 'normal'
txtParts[num].delete(0, END)
enternum = len(text[1]) // 57
enterdata = []
for i in range(enternum + 1):
enterdata.append(text[1][i * 57:i * 57 + 57])
for i in range(enternum + 1):
if i > 0:
num += 1
datanum += 1
if num > 17:
txtParts[17].delete(0, END)
datalist.append([enterdata[i], 'left'])
downbool = True
go_down()
else:
print(i)
print(num)
print(enterdata[i])
txtParts[num]['state'] = 'normal'
txtParts[num].config(justify='left')
txtParts[num].insert("end", enterdata[i])
datalist.append([enterdata[i], 'left'])
txtParts[num]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
txt = txtParts[17]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append([text[0] + text[1], 'left'])
downbool = True
go_down()
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
datalist.append([text[1], 'right'])
downbool = True
go_down()
else:
txt.config(justify='left')
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append([text[0], 'left'])
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
datalist.append([text[1], 'left'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global updownnum
if updownnum > 0:
updownnum -= 1
for i in range(17, -1, -1):
txtParts[i]['state'] = 'normal'
# datanum2에 justify 값 넣기([][])
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i+updownnum][0])
if datalist[i+updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i]['state'] = 'disabled'
def go_down():
global datalist
global updownnum
global datanum
global downbool
if updownnum + 18 <= datanum:
updownnum += 1
for i in range(0, 18):
txtParts[i]['state'] = 'normal'
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i+updownnum][0])
txtParts[i]['state'] = 'disabled'
# if downbool == True:
# txtParts[17]['state'] = 'normal'
# txtParts[17].config(justify='right')
# txtParts[17].delete(0, END)
# txtParts[17].insert("end", datalist[17 + updownnum])
# txtParts[17]['state'] = 'disabled'
# downbool = False
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x610')
c_root.title('client')
c_root.resizable(False, False)
start_new_thread(login, ())
frame = Frame(c_root, width=300)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
txtfont = tkFont.Font(size=10)
for i in range(0, 18):
x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black', background='#BECDFF')
x.pack()
x.configure(font=txtfont)
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=5)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', bg='white', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=500)
# message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
updownnum = 0
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
10
080927kdy
2022년 9월 18일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
import tkinter.font as tkFont
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
# 처음일때
global datalist
global datanum
global downbool
while True:
if num < 17:
num += 1
txt = txtParts[num]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.insert("end", text[0] + text[1])
datalist.append([text[0] + text[1], 'left'])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
txt.insert("end", text[1])
datalist.append([text[1], 'right'])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.insert("end", text[0])
datalist.append([text[0], 'left'])
if num == 17:
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
datalist.append([text[1], 'left'])
datanum += 1
downbool = True
go_down()
else:
txtParts[num + 1]['state'] = 'normal'
txtParts[num + 1].delete(0, END)
txtParts[num + 1].insert("end", text[1])
datalist.append([text[1], 'left'])
datanum += 1
num += 1
txtParts[num]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
txt = txtParts[17]
datanum += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append([text[0] + text[1], 'left'])
downbool = True
go_down()
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
datalist.append([text[1], 'right'])
downbool = True
go_down()
else:
txt.config(justify='left')
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append([text[0], 'left'])
downbool = True
go_down()
txtParts[17]['state'] = 'normal'
txtParts[17].delete(0, END)
datalist.append([text[1], 'left'])
datanum += 1
downbool = True
go_down()
txtParts[17]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global updownnum
if updownnum > 0:
updownnum -= 1
for i in range(17, -1, -1):
txtParts[i]['state'] = 'normal'
# datanum2에 justify 값 넣기([][])
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i+updownnum][0])
if datalist[i+updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i]['state'] = 'disabled'
def go_down():
global datalist
global updownnum
global datanum
global downbool
if updownnum + 18 <= datanum:
updownnum += 1
for i in range(0, 18):
txtParts[i]['state'] = 'normal'
if datalist[i + updownnum][1] == 'right':
txtParts[i].config(justify='right')
else:
txtParts[i].config(justify='left')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[i+updownnum][0])
txtParts[i]['state'] = 'disabled'
# if downbool == True:
# txtParts[17]['state'] = 'normal'
# txtParts[17].config(justify='right')
# txtParts[17].delete(0, END)
# txtParts[17].insert("end", datalist[17 + updownnum])
# txtParts[17]['state'] = 'disabled'
# downbool = False
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x610')
c_root.title('client')
c_root.resizable(False, False)
start_new_thread(login, ())
frame = Frame(c_root)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
txtfont = tkFont.Font(size=10)
for i in range(0, 18):
x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black', background='#BECDFF')
x.pack()
x.configure(font=txtfont)
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=5)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', bg='white', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=500)
# message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
updownnum = 0
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
3
080927kdy
2022년 9월 18일
In 소스 코드 제출
import socket
from _thread import *
from tkinter import *
def threaded(client_socket, addr):
global chat_log
global namebool
while namebool == True:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
name = str(data.decode())
namebool = False
chat_log['state'] = 'normal'
chat_log.insert("end", '[System] ' + name +' 님이 접속하였습니다.'+'\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall(('[System] ' + '☈' + name + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
chat_log.insert("end", name + ':' + '\n' + str(data.decode()) + '\n' + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall((name + '☈' + data.decode()).encode())
except ConnectionResetError as e:
c_list.remove(client_socket)
for c in c_list:
c.sendall(('[System] ' + name + ' 님이 나갔습니다.').encode())
chat_log['state'] = 'normal'
chat_log.insert("end", 'Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
break
client_socket.close()
def server_open():
HOST = ip_entry.get()
PORT = int(port_entry.get())
start_new_thread(make_server, (HOST, PORT))
open_button['state'] = 'disabled'
ip_entry['state'] = 'readonly'
port_entry['state'] = 'readonly'
def server_close():
exit()
def make_server(HOST, PORT):
global server_socket
global namebool
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
chat_log['state'] = 'normal'
chat_log.insert("end", 'Server Start\n')
chat_log['state'] = 'disabled'
while 1:
client_socket, addr = server_socket.accept()
namebool = True
c_list.append(client_socket)
start_new_thread(threaded, (c_list[-1], addr))
c_list = []
close = False
server_socket = None
namebool = True
s_root = Tk()
s_root.geometry('500x500')
s_root.title('Server')
s_root.resizable(False, False)
''' Top Menu '''
Label(s_root, text='Server IP : ').place(x=20, y=20)
Label(s_root, text='Port : ').place(x=250, y=20)
ip_entry = Entry(s_root, width=14)
ip_entry.place(x=83, y=21)
ip_entry.insert(0, '127.0.0.1')
port_entry = Entry(s_root, width=5)
port_entry.place(x=290, y=21)
port_entry.insert(0, '9999')
open_button = Button(s_root, text='Server Open', command=server_open)
open_button.place(x=380, y=18)
''' Middle Menu '''
chat_log = Text(s_root, width=65, height=29, state='disabled', spacing2=2)
chat_log.place(x=20, y=60)
''' Bottom Menu '''
close_button = Button(s_root, text='Server Close', command=server_close)
close_button.place(x=200, y=460)
s_root.mainloop()
0
0
9
080927kdy
2022년 9월 17일
In 소스 코드 제출
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
global num
global x
# 처음일때
global datalist
global datanum
global datanum2
while True:
if num < 17:
num += 1
txt = txtParts[num]
datanum += 1
datanum2 += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.insert("end", text[0] + text[1])
datalist.append(text[0] + text[1])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
txt.insert("end", text[1])
datalist.append(text[1])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
txt.insert("end", text[0])
datalist.append(text[0])
txtParts[num + 1]['state'] = 'normal'
txtParts[num + 1].delete(0, END)
txtParts[num + 1].insert("end", text[1])
datalist.append(text[1])
datanum += 1
datanum2 += 1
num += 1
txtParts[num]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
else:
# if num <= 0:
# num = 17
# else:
# num -= 1
txt = txtParts[17]
datanum += 1
datanum2 += 1
try:
data = socket.recv(1024)
txt['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append(text[0] + text[1])
go_down()
txt.insert("end", text[0] + text[1])
first = False
else:
if str(text[0]) == str(name):
txt.config(justify='right')
txt.delete(0, END)
datalist.append(text[1])
go_down()
txt.insert("end", text[0] + text[1])
else:
text[0].replace('☈', '').strip()
txt.delete(0, END)
datalist.append(text[0])
go_down()
txt.insert("end", text[0] + text[1])
num += 1
txtParts[num]['state'] = 'normal'
txtParts[num].delete(0, END)
datalist.append(text[1])
datanum += 1
datanum2 += 1
go_down()
txtParts[num]['state'] = 'disabled'
txt['state'] = 'disabled'
except ConnectionAbortedError as e:
txt['state'] = 'normal'
txt.delete(0, END)
txt.insert("end", '\n[System] 접속을 종료합니다.\n')
txt['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def go_up():
global datalist
global datanum2
# datanum2는 go, down에 따라 맨 밑(17번째칸)의 datalist값으로 바꿔야 함
if datanum2-18 != 0:
for i in range(17, -1, -1):
txtParts[i]['state'] = 'normal'
txtParts[i].config(justify='right')
# datanum2에 justify 값 넣기([][])
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[datanum2-(2+i)])
datanum2 -= 1
def go_down():
global datalist
global datanum2
for i in range(0, 18):
txtParts[i]['state'] = 'normal'
txtParts[i].config(justify='right')
txtParts[i].delete(0, END)
txtParts[i].insert("end", datalist[datanum2-(17-i)])
txtParts[i]['state'] = 'disabled'
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x525')
c_root.title('client')
c_root.resizable(False, False)
start_new_thread(login, ())
frame = Frame(c_root)
upbtn = Button(frame, text='up', command=go_up)
upbtn.pack(fill='x')
chat_canvas = Canvas(frame)
chat_canvas.pack()
downbtn = Button(frame, text='down', command=go_down)
downbtn.pack(fill='x')
txtParts = []
for i in range(0, 18):
x = Entry(chat_canvas, width=65, disabledbackground='#BECDFF', disabledforeground='black')
x.pack()
x['state'] = 'disabled'
txtParts.append(x)
frame.place(x=10, y=10)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', bg='white', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
message_frame.place(x=10, y=415)
# message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
num = -1
x = True
datalist = []
datanum = -1
downbool = False
upbool = False
datanum2 = -1
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
0
0
4
080927kdy
2022년 9월 17일
In 소스 코드 제출
client.py
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
c_list = []
close = False
server_socket = None
def log_in():
def sendname(socket):
global namebool
global name
name = nametxt.get()
socket.send(name.encode())
namebool = False
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
global space
global name
first = True
while True:
try:
data = socket.recv(1024)
chat_log['state'] = 'normal'
text = str(data.decode()).split('☈')
if first:
text[0].replace('☈', '').strip()
chat_log.insert("end", text[0] + text[1])
first = False
else:
if str(text[0]) == str(name):
msgnum = 65 - int(len(text[1]))
for i in range(msgnum):
# space = space + str(i % 10)
space = space + ' '
chat_log.insert("end", '\n' + '\n' + space + text[1])
space = ''
else:
text[0].replace('☈', '').strip()
chat_log.insert("end", '\n' + '\n' + text[0] + '\n' + text[1])
chat_log.see('end')
chat_log['state'] = 'disabled'
except ConnectionAbortedError as e:
chat_log['state'] = 'normal'
chat_log.insert("end", '\n[System] 접속을 종료합니다.\n')
chat_log['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = iptxt.get()
PORT = int(porttxt.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=sendname, args=(client_socket,)).start()
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def set_go_send(event):
global go_send
go_send = True
c_root = Toplevel(root)
c_root.geometry('500x525')
c_root.title('client')
c_root.resizable(False, False)
c_root['bg'] = '#BECDFF'
start_new_thread(login, ())
chat_frame = Frame(c_root)
scrollbar = Scrollbar(chat_frame)
scrollbar.pack(side='right', fill='y')
chat_log = Text(chat_frame, width=65, height=30, state='disabled', yscrollcommand=scrollbar.set)
chat_log.pack(side='left')
scrollbar['command'] = chat_log.yview
chat_frame.place(x=10, y=10)
message_frame = Frame(c_root)
message_input = Text(message_frame, width=57, height=7)
message_input.pack(side='left')
send_button = Button(message_frame, text='보내기', bg='white', command=lambda: set_go_send(None))
send_button.pack(side='right', fill='y')
send_button['bg'] = 'white'
message_frame.place(x=10, y=415)
# message_input.bind("<Return>", set_go_send)
c_root.mainloop()
go_out, go_send = False, False
root = Tk()
root.resizable(False, False)
root.title('로그인')
root.geometry("300x125-500+200")
namebool = True
space = ''
iplbl = Label(root, text="server IP", width=10)
iplbl.grid(row=0, column=0)
iptxt = Entry(root, width=20)
iptxt.insert(0, '127.0.0.1')
iptxt.grid(row=0, column=1)
portlbl = Label(root, text="port", width=10)
portlbl.grid(row=1, column=0)
porttxt = Entry(root, width=20)
porttxt.insert(0, '9999')
porttxt.grid(row=1, column=1)
namelbl = Label(root, text="이름", width=10)
namelbl.grid(row=2, column=0)
nametxt = Entry(root, width=20)
nametxt.grid(row=2, column=1)
btnlogin = Button(root, text="로그인", command=log_in)
btnlogin.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S)
root.mainloop()
server.py
import socket
from _thread import *
from tkinter import *
def threaded(client_socket, addr):
global chat_log
global namebool
while namebool == True:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
name = str(data.decode())
namebool = False
chat_log['state'] = 'normal'
chat_log.insert("end", '[System] ' + name +' 님이 접속하였습니다.'+'\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall(('[System] ' + '☈' + name + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
chat_log.insert("end", name + ':' + '\n' + str(data.decode()) + '\n' + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall((name + '☈' + data.decode()).encode())
except ConnectionResetError as e:
c_list.remove(client_socket)
for c in c_list:
c.sendall(('[System] ' + name + ' 님이 나갔습니다.').encode())
chat_log['state'] = 'normal'
chat_log.insert("end", 'Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
break
client_socket.close()
def server_open():
HOST = ip_entry.get()
PORT = int(port_entry.get())
start_new_thread(make_server, (HOST, PORT))
open_button['state'] = 'disabled'
ip_entry['state'] = 'readonly'
port_entry['state'] = 'readonly'
def server_close():
exit()
def make_server(HOST, PORT):
global server_socket
global namebool
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
chat_log['state'] = 'normal'
chat_log.insert("end", 'Server Start\n')
chat_log['state'] = 'disabled'
while 1:
client_socket, addr = server_socket.accept()
namebool = True
c_list.append(client_socket)
start_new_thread(threaded, (c_list[-1], addr))
c_list = []
close = False
server_socket = None
namebool = True
s_root = Tk()
s_root.geometry('500x500')
s_root.title('Server')
s_root.resizable(False, False)
''' Top Menu '''
Label(s_root, text='Server IP : ').place(x=20, y=20)
Label(s_root, text='Port : ').place(x=250, y=20)
ip_entry = Entry(s_root, width=14)
ip_entry.place(x=83, y=21)
ip_entry.insert(0, '127.0.0.1')
port_entry = Entry(s_root, width=5)
port_entry.place(x=290, y=21)
port_entry.insert(0, '9999')
open_button = Button(s_root, text='Server Open', command=server_open)
open_button.place(x=380, y=18)
''' Middle Menu '''
chat_log = Text(s_root, width=65, height=29, state='disabled', spacing2=2)
chat_log.place(x=20, y=60)
''' Bottom Menu '''
close_button = Button(s_root, text='Server Close', command=server_close)
close_button.place(x=200, y=460)
s_root.mainloop()
0
0
2
080927kdy
2022년 9월 03일
In 소스 코드 제출
import tkinter as tk
import socket
from _thread import *
c_list = []
close = False
server_socket = None
def createNewWindow():
def threaded(client_socket, addr):
global chat_log
chat_log['state'] = 'normal'
chat_log.insert("end", 'Connected by :' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
chat_log.insert("end",
'Received from ' + addr[0] + ' : ' + str(addr[1]) + ' :: ' + str(data.decode()) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
print(c)
print(client_socket)
print(1)
c.sendall((str(addr[1]) + ' : ' + data.decode()).encode())
except ConnectionResetError as e:
c_list.remove(client_socket)
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 나갔습니다.').encode())
chat_log['state'] = 'normal'
chat_log.insert("end", 'Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
break
client_socket.close()
def server_open():
HOST = ip_entry.get()
PORT = int(port_entry.get())
start_new_thread(make_server, (HOST, PORT))
open_button['state'] = 'disabled'
ip_entry['state'] = 'readonly'
port_entry['state'] = 'readonly'
def server_close():
exit()
def make_server(HOST, PORT):
global server_socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 포트사용중이라 연결할 수 없다는 WinError 10048 에러를 해결하기 위해 필요합니다.
# 서버 소켓의 SOL_SOCKET의 SO_REUSEADDR(이미 사용중인 포트에 대해서도 바인드 허용) 를 1(True)로 설정하는 것으로 이해
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print(server_socket)
server_socket.bind((HOST, PORT))
server_socket.listen()
chat_log['state'] = 'normal'
chat_log.insert("end", 'Server Start\n')
chat_log['state'] = 'disabled'
while 1:
print(1)
client_socket, addr = server_socket.accept()
print(client_socket, '111', addr)
c_list.append(client_socket)
start_new_thread(threaded, (c_list[-1], addr))
s_root = tk.Toplevel(root)
s_root.geometry('500x500')
s_root.title('Server')
s_root.resizable(False, False)
''' Top Menu '''
tk.Label(s_root, text='Server IP : ').place(x=20, y=20)
tk.Label(s_root, text='Port : ').place(x=250, y=20)
ip_entry = tk.Entry(s_root, width=14, text='14.33.178.121')
ip_entry.place(x=83, y=21)
ip_entry.insert(0, '14.33.178.121')
port_entry = tk.Entry(s_root, width=5, text='9999')
port_entry.place(x=290, y=21)
port_entry.insert(0, '9999')
open_button = tk.Button(s_root, text='Server Open', command=server_open)
open_button.place(x=380, y=18)
''' Middle Menu '''
chat_log = tk.Text(s_root, width=65, height=29, state='disabled', spacing2=2)
chat_log.place(x=20, y=60)
''' Bottom Menu '''
close_button = tk.Button(s_root, text='Server Close', command=server_close)
close_button.place(x=200, y=460)
s_root.mainloop()
root = tk.Tk()
root.title('login')
root.geometry('200x200')
lbl = tk.Label(root, text="server IP")
lbl.grid(row=0, column=0)
txt = tk.Entry(root)
txt.grid(row=0, column=1)
lbl = tk.Label(root, text="port")
lbl.grid(row=1, column=0)
txt = tk.Entry(root)
txt.grid(row=1, column=1)
btn = tk.Button(root, text="login", command=createNewWindow)
btn.grid(row=2, column=0)
root.mainloop()
http://pythonstudy.xyz/python/article/122-Tkinter-%EC%9D%B4%EB%B2%A4%ED%8A%B8
0
0
4
080927kdy
2022년 9월 03일
In 소스 코드 제출
server.py
import sys
import socket
# from tkinter import *
from _thread import *
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QHBoxLayout, QScrollArea, \
QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.hbox = QHBoxLayout()
self.hbox.addStretch(1)
self.iplbl = QLabel('Server ip:')
self.hbox.addWidget(self.iplbl)
self.iptxt = QLineEdit('127.0.0.1')
self.hbox.addWidget(self.iptxt)
self.iptxt.setMaximumWidth(100)
self.hbox.addStretch(1)
self.portlbl = QLabel('port:')
self.hbox.addWidget(self.portlbl)
self.porttxt = QLineEdit('9999')
self.porttxt.setMaximumWidth(50)
self.hbox.addWidget(self.porttxt)
self.hbox.addStretch(1)
self.serveropenbtn = QPushButton('server open')
self.serveropenbtn.clicked.connect(self.serveropen)
self.serveropenbtn.setCheckable(False)
self.serveropenbtn.toggle()
self.serveropenbtn.setMaximumWidth(100)
self.hbox.addWidget(self.serveropenbtn)
self.serverclosebtn = QPushButton('Server close')
self.serveropenbtn.clicked.connect(self.serverclose)
self.serverclosebtn.setCheckable(False)
self.serverclosebtn.toggle()
self.serverclosebtn.setMaximumWidth(100)
self.hbox.addWidget(self.serverclosebtn)
self.hbox.addStretch(1)
self.vbox.addLayout(self.hbox)
self.mtext = QTextEdit()
self.vbox.addWidget(self.mtext)
self.setLayout(self.vbox)
self.setWindowTitle('server')
self.move(300, 300)
self.setFixedSize(QSize(600, 500))
self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)
self.show()
def serveropen(self):
HOST = self.iptxt.text()
PORT = int(self.porttxt.text())
start_new_thread(self.make_server, (HOST, PORT))
# self.serveropenbtn['state'] = 'disabled'
# self.iptext['state'] = 'readonly'
# self.porttxt['state'] = 'readonly'
def serverclose(self):
exit()
def make_server(self, HOST, PORT):
global server_socket0
server_socket0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket0.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket0.bind((HOST, PORT))
server_socket0.listen()
# chat_log['state'] = 'normal'
self.mtext.setText('Server Start\n')
# chat_log['state'] = 'disabled'
while 1:
client_socket, addr = server_socket0.accept()
c_list0.append(client_socket)
start_new_thread(self.threaded, (c_list0[-1], addr))
def threaded(self, client_socket, addr):
global c_list0
# global chat_log
# chat_log['state'] = 'normal'
self.mtext.setText('Connected by :' + addr[0] + ':' + str(addr[1]) + '\n')
# chat_log['state'] = 'disabled'
for c in c_list0:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
# chat_log['state'] = 'normal'
self.mtext.setText('Received from ' + addr[0] + ' : ' + str(addr[1]) + ' :: ' + str(data.decode()) + '\n')
# chat_log['state'] = 'disabled'
for c in c_list0:
c.sendall((str(addr[1]) + ' : ' + data.decode()).encode())
except ConnectionResetError as e:
c_list0.remove(client_socket)
for c in c_list0:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 나갔습니다.').encode())
# chat_log['state'] = 'normal'
self.mtext.setText('Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
# chat_log['state'] = 'disabled'
break
client_socket.close()
c_list0 = []
close = False
server_socket0 = None
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
client.py
import sys
import socket
import threading
from time import sleep
from _thread import *
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QHBoxLayout, QScrollArea, QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.hbox = QHBoxLayout()
self.hbox.addStretch(1)
self.iplbl = QLabel('Server ip:')
self.hbox.addWidget(self.iplbl)
self.iptxt = QLineEdit('127.0.0.1')
self.hbox.addWidget(self.iptxt)
self.iptxt.setMaximumWidth(100)
self.hbox.addStretch(1)
self.portlbl = QLabel('port:')
self.hbox.addWidget(self.portlbl)
self.porttxt = QLineEdit('9999')
self.porttxt.setMaximumWidth(50)
self.hbox.addWidget(self.porttxt)
self.hbox.addStretch(1)
self.loginbtn = QPushButton('login')
self.loginbtn.clicked.connect(self.try_login)
self.loginbtn.setCheckable(False)
self.loginbtn.toggle()
self.loginbtn.setMaximumWidth(100)
self.hbox.addWidget(self.loginbtn)
self.logoutbtn = QPushButton('logout')
self.logoutbtn.clicked.connect(self.try_logout)
self.logoutbtn.setCheckable(False)
self.logoutbtn.toggle()
self.logoutbtn.setMaximumWidth(100)
self.hbox.addWidget(self.logoutbtn)
self.vbox.addLayout(self.hbox)
self.msgtext = QTextEdit()
self.vbox.addWidget(self.msgtext)
self.hbox2 = QHBoxLayout()
self.writetxt = QTextEdit()
self.writetxt.setMaximumHeight(100)
self.hbox2.addWidget(self.writetxt)
self.vbox2 = QVBoxLayout()
self.filebtn = QPushButton('file')
self.filebtn.setCheckable(False)
self.filebtn.toggle()
self.vbox2.addWidget(self.filebtn)
self.sendbtn = QPushButton('send')
self.sendbtn.setCheckable(False)
self.sendbtn.toggle()
self.sendbtn.clicked.connect(self.set_go_send)
self.vbox2.addWidget(self.sendbtn)
self.hbox2.addLayout(self.vbox2)
self.vbox.addLayout(self.hbox2)
self.setLayout(self.vbox)
self.setWindowTitle('client')
self.move(300, 300)
self.setFixedSize(QSize(600, 500))
self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)
self.show()
def send(self, socket):
global go_send
while True:
if go_send:
message = (self.writetxt.toPlainText()).rstrip()
socket.send(message.encode())
self.writetxt.setText('')
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(self, socket):
first = True
while True:
try:
data = socket.recv(1024)
if first: # 이걸 처음 체크 이후 의미없이 매번 체크하므로 이렇게 하는 건 효율적이지 않음.
self.msgtext.setText(str(data.decode()))
first = False
else:
self.msgtext.setText('\n' + str(data.decode()))
except ConnectionAbortedError as e:
self.msgtext.setText('\n[System] 접속을 종료합니다.\n')
exit()
def login(self):
# 서버의 ip주소 및 포트
HOST = self.iptxt.text()
PORT = int(self.porttxt.text())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=self.send, args=(client_socket,)).start()
threading.Thread(target=self.receive, args=(client_socket,)).start()
exit()
def try_login(self):
global go_out
start_new_thread(self.login, ())
# login_button['state'] = 'disabled'
# logout_button['state'] = 'active'
# ip_entry['state'] = 'readonly'
# port_entry['state'] = 'readonly'
go_out = False
def try_logout(self):
global go_out
# login_button['state'] = 'active'
# logout_button['state'] = 'disabled'
# ip_entry['state'] = 'normal'
# port_entry['state'] = 'normal'
go_out = True
def set_go_send(self, event):
global go_send
go_send = True
go_out, go_send = False, False
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
0
0
5
080927kdy
2022년 8월 27일
In 소스 코드 제출
https://chinpa.tistory.com/9
server.py
import sys
import socket
from tkinter import *
from _thread import *
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QHBoxLayout, QScrollArea, \
QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.hbox = QHBoxLayout()
self.hbox.addStretch(1)
self.iplbl = QLabel('Server ip:')
self.hbox.addWidget(self.iplbl)
self.iptxt = QLineEdit('14.33.178.245')
self.hbox.addWidget(self.iptxt)
self.iptxt.setMaximumWidth(100)
self.hbox.addStretch(1)
self.portlbl = QLabel('port:')
self.hbox.addWidget(self.portlbl)
self.porttxt = QLineEdit('9999')
self.porttxt.setMaximumWidth(50)
self.hbox.addWidget(self.porttxt)
self.hbox.addStretch(1)
self.vbox.addLayout(self.hbox)
self.scrArea = QScrollArea()
self.vbox.addWidget(self.scrArea)
self.hbox2 = QHBoxLayout()
self.serveropenbtn = QPushButton('server open')
self.serveropenbtn.clicked.connect(self.serveropen)
self.serveropenbtn.setCheckable(False)
self.serveropenbtn.toggle()
# self.serveropenbtn.setMaximumWidth(100)
self.hbox2.addWidget(self.serveropenbtn)
self.serverclosebtn = QPushButton('Server close')
self.serveropenbtn.clicked.connect(self.serverclose)
self.serverclosebtn.setCheckable(False)
self.serverclosebtn.toggle()
# self.serverclosebtn.setMaximumWidth(100)
self.hbox2.addWidget(self.serverclosebtn)
self.vbox.addLayout(self.hbox2)
self.setLayout(self.vbox)
self.setWindowTitle('server')
self.move(300, 300)
self.setFixedSize(QSize(500, 500))
self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)
self.show()
def serveropen(self):
HOST = self.iptxt.text()
PORT = int(self.porttxt.text())
start_new_thread(self.make_server, (HOST, PORT))
self.serveropenbtn['state'] = 'disabled'
self.iptext['state'] = 'readonly'
self.porttxt['state'] = 'readonly'
def serverclose(self):
exit()
def make_server(self, HOST, PORT):
global server_socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 포트사용중이라 연결할 수 없다는 WinError 10048 에러를 해결하기 위해 필요합니다.
# 서버 소켓의 SOL_SOCKET의 SO_REUSEADDR(이미 사용중인 포트에 대해서도 바인드 허용) 를 1(True)로 설정하는 것으로 이해
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
chat_log['state'] = 'normal'
chat_log.insert("end", 'Server Start\n')
chat_log['state'] = 'disabled'
while 1:
client_socket, addr = server_socket.accept()
c_list.append(client_socket)
start_new_thread(self.threaded, (c_list[-1], addr))
def threaded(self, client_socket, addr):
global chat_log
chat_log['state'] = 'normal'
chat_log.insert("end", 'Connected by :' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
chat_log.insert("end",
'Received from ' + addr[0] + ' : ' + str(addr[1]) + ' :: ' + str(data.decode()) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall((str(addr[1]) + ' : ' + data.decode()).encode())
except ConnectionResetError as e:
c_list.remove(client_socket)
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 나갔습니다.').encode())
chat_log['state'] = 'normal'
chat_log.insert("end", 'Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
break
client_socket.close()
c_list = []
close = False
server_socket = None
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
client.py
import socket
from _thread import *
import threading
from tkinter import *
from time import sleep
def send(socket):
global go_send
while True:
if go_send:
message = (message_input.get(1.0, "end")).rstrip()
socket.send(message.encode())
message_input.delete(1.0, "end")
go_send = False
else:
if go_out:
socket.close()
exit()
sleep(0.1)
def receive(socket):
first = True
while True:
try:
data = socket.recv(1024)
chat_log['state'] = 'normal'
if first: # 이걸 처음 체크 이후 의미없이 매번 체크하므로 이렇게 하는 건 효율적이지 않음.
chat_log.insert("end", str(data.decode()))
first = False
else:
chat_log.insert("end", '\n' + str(data.decode()))
chat_log.see('end')
chat_log['state'] = 'disabled'
except ConnectionAbortedError as e:
chat_log['state'] = 'normal'
chat_log.insert("end", '\n[System] 접속을 종료합니다.\n')
chat_log['state'] = 'disabled'
exit()
def login():
# 서버의 ip주소 및 포트
HOST = ip_entry.get();
PORT = int(port_entry.get())
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
threading.Thread(target=send, args=(client_socket,)).start()
threading.Thread(target=receive, args=(client_socket,)).start()
exit()
def try_login():
global go_out
start_new_thread(login, ())
login_button['state'] = 'disabled'
logout_button['state'] = 'active'
ip_entry['state'] = 'readonly'
port_entry['state'] = 'readonly'
go_out = False
def try_logout():
global go_out
login_button['state'] = 'active'
logout_button['state'] = 'disabled'
ip_entry['state'] = 'normal'
port_entry['state'] = 'normal'
go_out = True
def set_go_send(event):
global go_send
go_send = True
go_out, go_send = False, False
c_root = Tk()
c_root.geometry('500x500')
c_root.title('Client')
c_root.resizable(False, False)
''' Top Menu '''
Label(c_root, text='Server IP : ').place(x=20, y=20)
Label(c_root, text='Port : ').place(x=250, y=20)
ip_entry = Entry(c_root, width=14);
ip_entry.place(x=83, y=21)
ip_entry.insert(0, '14.33.178.245')
port_entry = Entry(c_root, width=5);
port_entry.place(x=290, y=21)
port_entry.insert(0, '9999')
login_button = Button(c_root, text='Log In', command=try_login);
login_button.place(x=350, y=18)
logout_button = Button(c_root, text='Log Out', state='disabled', command=try_logout);
logout_button.place(x=420, y=18)
''' Middle Menu '''
chat_frame = Frame(c_root)
scrollbar = Scrollbar(chat_frame);
scrollbar.pack(side='right', fill='y')
chat_log = Text(chat_frame, width=62, height=24, state='disabled', yscrollcommand=scrollbar.set);
chat_log.pack(side='left') # place(x=20, y=60)
scrollbar['command'] = chat_log.yview
chat_frame.place(x=20, y=60)
message_input = Text(c_root, width=55, height=4);
message_input.place(x=20, y=390)
send_button = Button(c_root, text='Send', command=lambda: set_go_send(None));
send_button.place(x=430, y=405)
message_input.bind("<Return>", set_go_send)
''' Bottom Menu '''
close_button = Button(c_root, text='Close', command=exit);
close_button.place(x=200, y=460)
c_root.mainloop()
0
0
11
080927kdy
2022년 8월 27일
In 소스 코드 제출
import sys
import socket
from tkinter import *
from _thread import *
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QHBoxLayout, QScrollArea, \
QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.hbox = QHBoxLayout()
self.hbox.addStretch(1)
self.iplbl = QLabel('Server ip:')
self.hbox.addWidget(self.iplbl)
self.iptxt = QLineEdit('14.33.178.245')
self.hbox.addWidget(self.iptxt)
self.iptxt.setMaximumWidth(100)
self.hbox.addStretch(1)
self.portlbl = QLabel('port:')
self.hbox.addWidget(self.portlbl)
self.porttxt = QLineEdit('9999')
self.porttxt.setMaximumWidth(50)
self.hbox.addWidget(self.porttxt)
self.hbox.addStretch(1)
self.vbox.addLayout(self.hbox)
self.scrArea = QScrollArea()
self.vbox.addWidget(self.scrArea)
self.hbox2 = QHBoxLayout()
self.serveropenbtn = QPushButton('server open')
self.serveropenbtn.clicked.connect(self.serveropen)
self.serveropenbtn.setCheckable(False)
self.serveropenbtn.toggle()
# self.serveropenbtn.setMaximumWidth(100)
self.hbox2.addWidget(self.serveropenbtn)
self.serverclosebtn = QPushButton('Server close')
self.serveropenbtn.clicked.connect(self.serverclose)
self.serverclosebtn.setCheckable(False)
self.serverclosebtn.toggle()
# self.serverclosebtn.setMaximumWidth(100)
self.hbox2.addWidget(self.serverclosebtn)
self.vbox.addLayout(self.hbox2)
self.setLayout(self.vbox)
self.setWindowTitle('server')
self.move(300, 300)
self.setFixedSize(QSize(500, 500))
self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)
self.show()
def serveropen(self):
HOST = self.iptxt.text()
PORT = int(self.porttxt.text())
start_new_thread(self.make_server, (HOST, PORT))
self.serveropenbtn['state'] = 'disabled'
self.iptext['state'] = 'readonly'
self.porttxt['state'] = 'readonly'
def serverclose(self):
exit()
def make_server(self, HOST, PORT):
global server_socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 포트사용중이라 연결할 수 없다는 WinError 10048 에러를 해결하기 위해 필요합니다.
# 서버 소켓의 SOL_SOCKET의 SO_REUSEADDR(이미 사용중인 포트에 대해서도 바인드 허용) 를 1(True)로 설정하는 것으로 이해
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
chat_log['state'] = 'normal'
chat_log.insert("end", 'Server Start\n')
chat_log['state'] = 'disabled'
while 1:
client_socket, addr = server_socket.accept()
c_list.append(client_socket)
start_new_thread(self.threaded, (c_list[-1], addr))
def threaded(self, client_socket, addr):
global chat_log
chat_log['state'] = 'normal'
chat_log.insert("end", 'Connected by :' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 접속하였습니다.').encode())
while 1:
try:
data = client_socket.recv(1024)
chat_log['state'] = 'normal'
chat_log.insert("end",
'Received from ' + addr[0] + ' : ' + str(addr[1]) + ' :: ' + str(data.decode()) + '\n')
chat_log['state'] = 'disabled'
for c in c_list:
c.sendall((str(addr[1]) + ' : ' + data.decode()).encode())
except ConnectionResetError as e:
c_list.remove(client_socket)
for c in c_list:
c.sendall(('[System] ' + str(addr[1]) + ' 님이 나갔습니다.').encode())
chat_log['state'] = 'normal'
chat_log.insert("end", 'Disconnected by ' + addr[0] + ':' + str(addr[1]) + '\n')
chat_log['state'] = 'disabled'
break
client_socket.close()
c_list = []
close = False
server_socket = None
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
0
0
4
080927kdy
2022년 8월 20일
In 소스 코드 제출
#https://github.com/kairess/socket-chat
#(anaconda) activate pythonProject. cd 파일경로. python server/client.py
<client.py>
import socket
import select
import sys
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8000))
name = None
while True:
read, write, fail = select.select((s,),(),(),1)
if msvcrt.kbhit(): read.append(sys.stdin)
for desc in read:
if desc == s:
data = s.recv(4096)
print(data.decode())
if name is None:
name = data.decode()
s.send(f'{name} is connected!'.encode())
else:
msg = desc.readline()
msg = msg.replace('\n', '')
s.send(f'{name} {msg}'.encode())
v = open('주소/save.txt')
save = v.readlines()
for line in save:
line = line.strip()
v.close()
v2 = open('주소/save2.txt')
num = v2.readline()
v2.close()
num = int(num)
save.append(msg)
num += 1
v = open('주소/save.txt', 'w')
for i in range(num):
v.write(save[i])
v.write('\n')
v.close()
v2 = open('주소/save2.txt', 'w')
v2.write(str(num))
v2.close()
#save.txt: 채팅 메세지 저장, save2.txt: num 값 저장(초기 값: 0)
<server.py>
from twisted.internet import protocol, reactor
import names
COLORS = [
'\033[31m', # RED
'\033[32m', # GREEN
'\033[33m', # YELLOW
'\033[34m', # BLUE
'\033[35m', # MAGENTA
'\033[36m', # CYAN
'\033[37m', # WHITE
'\033[4m', # UNDERLINE
]
transports = set()
users = set()
class Chat(protocol.Protocol):
def connectionMade(self):
name = names.get_first_name()
color = COLORS[len(users) % len(COLORS)]
users.add(name)
transports.add(self.transport)
self.transport.write(f'{name}'.encode())
def dataReceived(self, data):
for t in transports:
if self.transport is not t:
t.write(data)
class ChatFactory(protocol.Factory):
def buildProtocol(self, addr):
return Chat()
print('Server started!')
reactor.listenTCP(8000, ChatFactory())
reactor.run()
0
0
4
080927kdy
2022년 8월 13일
In 소스 코드 제출
server.py
#https://github.com/kairess/socket-chat
#(anaconda) activate pythonProject. cd 파일경로. python server/client.py
from twisted.internet import protocol, reactor
import names
COLORS = [
'\033[31m', # RED
'\033[32m', # GREEN
'\033[33m', # YELLOW
'\033[34m', # BLUE
'\033[35m', # MAGENTA
'\033[36m', # CYAN
'\033[37m', # WHITE
'\033[4m', # UNDERLINE
]
transports = set()
users = set()
class Chat(protocol.Protocol):
def connectionMade(self):
name = names.get_first_name()
color = COLORS[len(users) % len(COLORS)]
users.add(name)
transports.add(self.transport)
self.transport.write(f'{name}'.encode())
def dataReceived(self, data):
for t in transports:
if self.transport is not t:
t.write(data)
class ChatFactory(protocol.Factory):
def buildProtocol(self, addr):
return Chat()
print('Server started!')
reactor.listenTCP(8000, ChatFactory())
reactor.run()
client.py
import msvcrt
import socket
import select
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8000))
name = None
while True:
read, write, fail = select.select((s,), (), (), 1)
if msvcrt.kbhit(): read.append(sys.stdin)
for desc in read:
print('what is desc', desc)
print('what is read', read)
if desc == s:
data = s.recv(4096)
print(data.decode())
if name is None:
name = data.decode()
s.send(f'{name} is connected!'.encode())
else:
msg = desc.readline()
msg = msg.replace('\n', '')
print(msg)
s.send(f'{name} {msg}'.encode())
0
0
7
080927kdy
더보기
bottom of page